Presentation is loading. Please wait.

Presentation is loading. Please wait.

 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.

Similar presentations


Presentation on theme: " Introduction to Search Algorithms  Linear Search  Binary Search 9-2."— Presentation transcript:

1

2  Introduction to Search Algorithms  Linear Search  Binary Search 9-2

3  Search : locating an item (key) in a list (array, vector, etc.).  Return yes/no  Return position (index) of match (-1 for not match)  Return object where key matches 9-3

4  Array numlist contains  When key = 11, linear search examines 17, 23, 5, and 11  When key = 7, linear search examines 17, 23, 5, 11, 2, 29, and 3 9-4 17235112293

5 int search(list[], int count, int key) found  false position  –1 index  0 While (index < count and !found) If (key == list[index]) Then found  true position  index End If index  index + 1 End While Return position 9-5

6  Benefits  Easy algorithm to understand  Array can be in any order  Disadvantage  Inefficient (slow): For array of N elements,  examines N/2 elements on average for value that is found in the array,  Examines N elements for value that is not in the array 9-6

7 1. Requirement: List is sorted 2. Divide a sorted list into three sections: 1.middle element 2.elements on left side of the middle element 3.elements on the right side of the middle element 3. If the middle element is the correct value, done. Otherwise, go to step 1, using only the half of the array that may contain the correct value. 4. Continue steps 1 and 2 until either the value is found or there are no more elements to examine. 9-7

8 9-8 0123456789 691215161920232528 List must be sorted LoMidHi Key: 25 Lo Mid Lo Mid If a key is not present in the list, when does the algorithm stop searching?

9 9-9 Given: list of N items What is the maximum number of comparisons? Number of Items comparisons remaining Example 0 N 1024 (2 10 ) 1 N(1/2) 512 (2 9 ) 2 N(1/2)(1/2) 256 (2 8 ) 2 N(1/2)(1/2)(1/2) 128 (2 7 ) 3 N(1/2) 4 64 (2 6 ) 4 N(1/2) 5 32 (2 5 ) 5............... k N(1/2) k 1

10 9-10 N(1/2) k = 1 N(1 k /2 k ) = 1 N(1/2 k ) = 1 N = 2 k log 2 N = log 2 (2 k ) log 2 N = k∙log 2 (2) log 2 N = k For N = 1024 (2 10 ), k = 10 For N = 1024,000 (2 20 ), k = 20

11 9-11 bool search(int a[], int count, int key) { int lo = 0; int hi = count - 1; bool found = false; int mid; while (lo <= hi && !found) { mid = (lo + hi) / 2; if (key == a[mid]) found = true; else if (key < a[mid]) hi = mid - 1; else // key > a[mid] lo = mid + 1; } return found; }


Download ppt " Introduction to Search Algorithms  Linear Search  Binary Search 9-2."

Similar presentations


Ads by Google