notes115

notes115 - CS 251 CLASS NOTES Created by John A Cotiguala...

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

View Full Document Right Arrow Icon
CS 251 CLASS NOTES Created by John A. Cotiguala Binary Search search for an element in a sorted sequence (array) sort array first useful when there are many lookups without interleaving inserts, Lookup tables and dictionary's that do not change very much narrows down the search range ny half in each iteration 2 4 7 8 9 12 17 19 22 28 30 low high Find(19); middle = (low + high)/2 = (0+10)/2 = 5 a[5] = 12 < 19 low = middle + 1 = 6 middle = (low + high)/2 = (6+10)/2 = 8 a[8] = 22 > 19 high = middle - 1 = 7 middle = (low + high)/2 = (6+7)/2 = 6 a[6] = 17 < 19 etc. .. Implementation of Binary Search class DictEntry { int _key; Object _element; } class Dictionary { DictEntry _entries[]; int _numEntries; Dictionary(int maxEntries) { _entries = new DictEntries[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;
Background image of page 1

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

View Full DocumentRight Arrow Icon
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);
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.

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

Page1 / 8

notes115 - CS 251 CLASS NOTES Created by John A Cotiguala...

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