Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linear search A linear search sequentially moves through your list looking for a matching value. 1. The element is found, i.e. a[i] = x. 2. The entire.

Similar presentations


Presentation on theme: "Linear search A linear search sequentially moves through your list looking for a matching value. 1. The element is found, i.e. a[i] = x. 2. The entire."— Presentation transcript:

1 Linear search A linear search sequentially moves through your list looking for a matching value. 1. The element is found, i.e. a[i] = x. 2. The entire array has been scanned, and no match was found. i=0; while (i<n && a[i]≠x) i++; O(n)

2 There are three conditions: А[mid]==key A[mid]<key A[mid]>key
Binary Search The key idea is to inspect a middle element and to compare it with the search argument key. There are three conditions: А[mid]==key A[mid]<key A[mid]>key

3 Example: А[10], key=16. left= 0 right= 9 mid = 4 16>A[mid] left= 5 mid = 7 16<A[mid] right= 6 mid = 5 16=A[mid]

4 SORTING Sorting is the process of rearranging a set of objects in a specific order. Internal sorting (sorting of arrays) External sorting (sorting of sequential files) Simple Sorting methods: insertion Sort selection Sort exchange Sort

5 Insertion sort The items are divided into a sorted sequence a[0] ... a[i-1] and a source sequence a[i] ... a[n-1]. FOR i := 1 TO n-1 DO x := a[i]; insert x at the appropriate place in a[0] ... a[i] END

6 Insertion sort А = 18, 20, 5, 13, 15

7 Insertion sort for (i=1; i<n; i++) { j=i; temp=a[i];
while(j>0 && temp<a[j-1]) a[j]=a[j-1]; j--; } a[j]=temp; //i determines sequence a[0]...a[i] //moving // insert

8 Insertion sort O(n2)

9 Binary insertion sort O(n2) void binsort(int a[], int n) {int item;
for (int i=1; i<n; i++) { item=a[i]; int l=0; int r=i-1; while (l<=r) int m=(l+r)/2; if (item<a[m]) r=m-1; else l=m+1; } for (int j=i-1; j>=l; j--) a[j+1]=a[j]; a[l]=item; }} O(n2)

10 Insertion Sort by Diminishing Increment
1, 4, 13, 40, 121, ... hk-1 = 3hk+1, ht-1 = 1, t = log3(n) - 1. 1, 3, 7, 15, 31, ... hk-1 = 2hk+1, ht-1 = 1, t = log2(n) - 1.


Download ppt "Linear search A linear search sequentially moves through your list looking for a matching value. 1. The element is found, i.e. a[i] = x. 2. The entire."

Similar presentations


Ads by Google