100 likes | 109 Views
Lecture 11. Searching Linear Search Binary Search recursive iterative polymorphic. Searching. One of the most common and important application areas The problem: Data is stored in a list of records, each of which includes a distinct identifying key
E N D
Lecture 11 • Searching • Linear Search • Binary Search • recursive • iterative • polymorphic
Searching • One of the most common and important application areas • The problem: • Data is stored in a list of records, each of which includes a distinct identifying key • Given a key (called the target), determine whether the list contains a record with key=target and, if so, return its location in the list
Searching • Very time consuming • a common operation • lists may be very large • even small improvements pay off • Not all searches are created equal... • Searching in unordered lists (sequential search) • Searching in ordered lists (binary search) • searching for patterns in text (various algorithms) • Internal searching vs. External searching
Sequential Search • If list is not ordered or organized in any particular way, this is the only method: • Algorithm: Compare target to the key of each item in list until either: • target is found (return location) • the list is exhausted (signal “not found”) • O(n) • Java code
Binary Search - sketch • For ordered lists only Compare target to the key of item in the middle of the list Three cases: • Equal: target is found (return location) • Less: search first sublist • Greater: Search second sublist
Binary Search - Recursive algorithm If list has at least one item: {Compare target to the key of item in the middle of the list Three cases: • Equal: target is found (return location) • Less: search first sublist • Greater: Search second sublist } else signal “not found”
Binary search • Much more efficient than sequential search • O(lg n) • Java code for recursive version
Binary Search - iterative version • Eliminate recursion by keeping track of current search interval in two variables (low and high) • Algorithm (given list a[0]..a[n-1]): • low = 0 • high = n • while low <high (we still have at least one item) • mid = (low+high)/2 • compare target to the key of a[mid]. Three cases: • Equal: return location (target is found) • Less: high = mid (search first sublist) • Greater: low = mid+1 (Search second sublist)
Binary search - iterative version • Still same efficiency class: O(lg n) • Java code for iterative version • Java code for polymorphic version
Sequential Search Slow - O(n) Linked or array implementation Applicable to any list Easier to implement low overhead Binary Search Fast - O(lg n) array implementation only list must be ordered Comparison of Searching methods