Notes114 - CS 251 Data Structures Class Notes Feb 25~Mar 1 Binary Search • Search for an element in an sorted sequence(array • sort array first

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 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; } 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...
View Full Document

This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 13

Notes114 - CS 251 Data Structures Class Notes Feb 25~Mar 1 Binary Search • Search for an element in an sorted sequence(array • sort array first

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online