90 likes | 187 Views
Standard Searches. by Ken Nguyen 2011. Searches. Given a list of n elements and a key k value to search against the list Two outcomes: Location of the key in the list or NOT_FOUND The searching schemes depend on the organization of the data in the list. Sequential Search.
E N D
Standard Searches by Ken Nguyen 2011
Searches • Given a list of n elements and a key k value to search against the list • Two outcomes: Location of the key in the list or NOT_FOUND • The searching schemes depend on the organization of the data in the list
Sequential Search • Comparing the key k to each of the element in the list. • It’ll take n comparisons to determine whether the key element is in the list or not. • This algorithm works for all any list of n elements
Sequential Search Algorithm Analysis: Step 1 and 3 are done once Step 2 is done n times when k is not in A Best case: k is the first element Worst case: kis not in A Input: a. List A of n elements, n ≥ 0 b. Key k Operations: 1. Let i = 0 2. While i < n do If k = A[i] RETURN I STOP Else i i + 1 End while 3. Return NOT_FOUND
Binary Search • Given a sorted list of n elements and a key value to search against the list • Compare the key to the element e located in the middle of the list as long as the list is NOT EMPTY • Three possible outcomes: • key = e RETURN the location of e and STOP • key < e repeat the search on the sublist containing elements with lower index than e • key> e repeat the search on the sublist containing elements with higher index than e
Binary Search Algorithm Analysis: Step 1 and 3 are done once Step 2 is done lgn times when k is not in A Best case: k is the element located in the middle of A Worst case: kis not in A Input: a. Ascending sorted list A of n elements, n ≥ 0 b. Key k Operations: 1. Let low = 0, hi = n 2. While low < hi do mid = ceil[(low + hi ) /2] If k = A[mid ] RETURN mid STOP Else if k< A[ mid ] hi mid -1 Else low mid +1 End while 3. Return NOT_FOUND
Example • Atlanta metropolitan with a population about 5M=5*106, and each person has 2 phone numbers. • The telco computer can perform 1M = 106 phone lookups per second. How long will it take for the telco to recognize you are dialing an in active number? • Sequential Search: (5*106 * 2) / 106 about 10s using seq. search
Binary Search: 22/106 about 0.000022s Would it be any significant slow down if n = 100M?
Choosing Your Search Use binary search will fail when the input data is not sorted If the data is searched once or few times, sequential search may be better since no sorting overhead is needed. Some data types CAN NOT be sorted in order.