18.10.2014 Views

COSC 1P03 Data Structures and Abstraction 20.1

COSC 1P03 Data Structures and Abstraction 20.1

COSC 1P03 Data Structures and Abstraction 20.1

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>COSC</strong> <strong>1P03</strong><br />

<strong>Data</strong> <strong>Structures</strong> <strong>and</strong> <strong>Abstraction</strong><br />

<strong>COSC</strong> <strong>1P03</strong><br />

Binary Search<br />

<br />

<br />

<br />

<br />

<br />

<br />

Large collections<br />

e.g. telephone book<br />

Requires - sorted by key<br />

Principle<br />

distribution of keys?<br />

probe at midpoint<br />

Algorithm<br />

probing<br />

bounds<br />

termination<br />

Analysis<br />

worst case<br />

each probe eliminates 1/2 remaining entries<br />

O(log n)<br />

E.g. view students<br />

<strong>Data</strong> <strong>Structures</strong> <strong>and</strong> <strong>Abstraction</strong> 20.7<br />

start with bounds being first <strong>and</strong> last items;<br />

while ( true ) {<br />

if ( bounds empty ) { not found; break; };<br />

access middle item between bounds<br />

if ( search key matches key on item ) { found; break; };<br />

if ( search key greater than key on item ) {<br />

set lower bound to next item<br />

}<br />

else {<br />

set upper bound to prior item<br />

};<br />

};<br />

Figure 20.4 Binary search algorithm<br />

lower<br />

bound<br />

new upper<br />

bound<br />

upper<br />

bound<br />

probe<br />

Figure 20.5 Probe in binary search<br />

20.3

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!