15.04.2018 Views

programming-for-dummies

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

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

Sequential Search 413<br />

Binary searching<br />

A variation of block searching is binary searching, which essentially uses a<br />

block half the size of the list. After dividing a list in half, the algorithm compares<br />

the last value of the first half of the list. If this value is smaller than the<br />

value it’s trying to find, the algorithm knows to search the second list instead.<br />

Otherwise, it searches the first half of the list.<br />

The algorithm repeatedly divides the list in half and searches only the list<br />

that contains the range of values it’s trying to find. Eventually, the binary<br />

search finds the data, as shown in Figure 2-4.<br />

18 46 89 93 102 146 198<br />

18 46 89 93 102 146 198<br />

Figure 2-4:<br />

Binary<br />

searching<br />

divides a list<br />

in half until<br />

it eventually<br />

finds its<br />

data.<br />

93 102<br />

93 102<br />

146 198<br />

Binary searching keeps dividing a list in half<br />

until it eventually finds the data, such as finding<br />

the number 102.<br />

The binary search algorithm works like this:<br />

1. Divide a sorted list in half.<br />

2. Compare the last value of the first half of the list.<br />

If this last value is less than the desired value, search this half of the list.<br />

Otherwise, search the other half of the list.<br />

3. Repeat Steps 1 and 2 until the desired value is found or confirmed not<br />

to exist.<br />

Book IV<br />

Chapter 2<br />

Searching<br />

Algorithms

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

Saved successfully!

Ooh no, something went wrong!