{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

notes114 - CS 251 Data Structures Class Notes Feb 25~Mar 1...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 251 Data Structures Class Notes Feb 25~Mar 1 _________________________________________________ Binary Search Search for an element in an sorted sequence(array) sort array first useful when there are many lookups without any interleaving inserts. Lookup tables and dictionaries that do not change much How does it work? Narrow down the search range by half in each iteration Ex . 0 1 2 3 4 5 6 7 8 9 10 11 (index) 2 4 7 8 9 12 17 19 22 25 28 37 (element) || || low high Find(19); Find middle = (11+0)/2 = 5 a[5] = 12 < 19 low = mid +1 = 6 mid = (6+11)/2 = 8 a[8] = 22 >19 high = 8-1 = 7 mid = 8+7 = 6 a[6] = 17 < 19 low = 6+1=7 mid = (7+7)/2=7 a[7]=19 = 19 Found it! Implementation class DictEntry { int _key; Object _element; }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
class dictionary { DictEntry _entries[]; int _numEntries; Dictionary(int maxEntries) { _entries = new DicEntry[maxEntries]; _numEntries = 0; } //we assume that entries have been inserted and sorted before being searched. Object binSearch(int key, int low, int high) { if ( low > high ) //key not found return null; else { int middle = (low+high)/2; if ( _entries[middle]._key = key) return _entries[middle]._element; else if ( _entries[middle]._key < key ) return binSearch(key,middle+1,high); else return binSearch(key,low,middle-1); } Running time of Binary Search The running time of candidate items is halved after each comparison
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}