Searching Dr Jose Annunziato Linear Search Linear search
- Slides: 10
Searching Dr. Jose Annunziato
Linear Search • Linear search iterates over an array sequentially searching for a matching element int linear. Search(int haystack[], int size, int needle) { for ( int k = 0; k < size; k++ ) O(n) if ( haystack [ k ] == needle ) return k; return -1; } n = 10 t~n 0 1 2 3 4 5 6 7 8 9 12 34 45 56 67 78 89 90 123 234
Binary Search • Binary search assumes array is sorted and progressively reduces search size in half • Consider searching for 123 in the following array 12 34 45 56 67 78 89 90 123 234 123 • Let's look at iterative and recursive implementation
int binary. Search ( int a[], int low, int high, int target ) { while (low <= high) { int middle = low + (high - low)/2; if (target < a[middle]) high = middle - 1; else if (target > a[middle]) low = middle + 1; else return middle; } return -1; }
Using Binary Search int main() { int array[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 123}; int result = binary. Search(array, 0, 9, 89); cout << "Found at: " << result << endl; getch(); }
Recursive Binary Search int binary. Search. Rec ( int a[], int low, int high, int target ) { if (high < low) return -1; int middle = (low + high)/2; if (target < a[middle]) return binary. Search. Rec(a, low, middle-1, target); else if (target > a[middle]) return binary. Search. Rec(a, middle+1, high, target); else if (target == a[middle]) return middle; }
Using Recursive Binary Search int main() { int array[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 123}; int result = binary. Search. Rec(array, 0, 9, 89); cout << "Found at: " << result << endl; getch(); }
Performance of Binary Search binary. Search. Rec(array, 0, 7, 45); n=8 0 1 2 3 4 5 6 7 12 34 45 56 67 78 89 90 0 1 2 3 12 34 45 56 2 3 45 56 h=3 2 45 • Height has something to do with # of comparisons
Performance of Binary Search n = 16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 3 7 9 11 17 23 32 34 43 45 54 56 65 67 76 0 1 2 3 4 5 6 7 1 3 7 9 11 17 23 32 4 5 6 7 11 17 23 32 6 7 23 32 4 = log 2( 16 ) h = log 2 n O(lg n) 6 23 h=4
Linear Search Vs. Binary Search t t~n O(n) t ~ log 2 (n) O ( ln n ) n
- Annunziato, jose
- Jose annunziato
- "augusto branco" -josé -jose
- Search by image
- What is sequential search
- Searching for solutions in artificial intelligence
- Searching adalah
- Internet searching techniques
- Orthogonal range searching
- Solving problem by searching
- While the csi team is searching the crime scene, _____.