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.

412<br />

Sequential Search<br />

Block searching<br />

Another technique to speed up sequential searching on sorted data is jump,<br />

or block searching. Rather than search one item at a time, this method jumps<br />

over a fixed number of items (such as five) and then examines the last item:<br />

✦ If this last item is greater than the value the algorithm is trying to<br />

find, the algorithm starts searching backward.<br />

✦ If this last item is less than the value the algorithm is trying to find,<br />

the algorithm jumps another block <strong>for</strong>ward, as shown in Figure 2-3.<br />

Figure 2-3:<br />

Jump, or<br />

block,<br />

searching<br />

can speed<br />

up a<br />

sequential<br />

search on<br />

sorted data.<br />

18 46 89 93 102 146 198<br />

Searching <strong>for</strong> the number 102 takes four<br />

jumps in a normal sequential search.<br />

18 46 89 93 102 146 198<br />

Searching <strong>for</strong> the number 102 can only<br />

take two jumps in a block search.<br />

The block searching algorithm works like this:<br />

1. Jump ahead a fixed number of items (a block).<br />

2. Compare the last value of the block:<br />

• If this value is less than the data to find, search sequentially within<br />

the block.<br />

• Otherwise, jump to the end of a new block and repeat Step 2.<br />

The basic idea behind block searching is to skip ahead through a sorted list<br />

of data and then slow down when it gets closer to that data. This is like looking<br />

through a telephone book <strong>for</strong> the name Winston Smith by skipping every<br />

ten pages until you reach the S section and then searching sequentially until<br />

you find the name Smith and finally the name Winston Smith.<br />

Block searching can work only with sorted data. If data isn’t sorted, block<br />

searching can’t work at all.

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

Saved successfully!

Ooh no, something went wrong!