412 Sequential Search Block searching Another technique to speed up sequential searching on sorted data is jump, or block searching. Rather than search one item at a time, this method jumps over a fixed number of items (such as five) and then examines the last item: ✦ If this last item is greater than the value the algorithm is trying to find, the algorithm starts searching backward. ✦ If this last item is less than the value the algorithm is trying to find, the algorithm jumps another block forward, as shown in Figure 2-3. Figure 2-3: Jump, or block, searching can speed up a sequential search on sorted data. 18 46 89 93 102 146 198 Searching for the number 102 takes four jumps in a normal sequential search. 18 46 89 93 102 146 198 Searching for the number 102 can only take two jumps in a block search. The block searching algorithm works like this: 1. Jump ahead a fixed number of items (a block). 2. Compare the last value of the block: • If this value is less than the data to find, search sequentially within the block. • Otherwise, jump to the end of a new block and repeat Step 2. The basic idea behind block searching is to skip ahead through a sorted list of data and then slow down when it gets closer to that data. This is like looking through a telephone book for the name Winston Smith by skipping every ten pages until you reach the S section and then searching sequentially until you find the name Smith and finally the name Winston Smith. Block searching can work only with sorted data. If data isn’t sorted, block searching can’t work at all.
Sequential Search 413 Binary searching A variation of block searching is binary searching, which essentially uses a block half the size of the list. After dividing a list in half, the algorithm compares the last value of the first half of the list. If this value is smaller than the value it’s trying to find, the algorithm knows to search the second list instead. Otherwise, it searches the first half of the list. The algorithm repeatedly divides the list in half and searches only the list that contains the range of values it’s trying to find. Eventually, the binary search finds the data, as shown in Figure 2-4. 18 46 89 93 102 146 198 18 46 89 93 102 146 198 Figure 2-4: Binary searching divides a list in half until it eventually finds its data. 93 102 93 102 146 198 Binary searching keeps dividing a list in half until it eventually finds the data, such as finding the number 102. The binary search algorithm works like this: 1. Divide a sorted list in half. 2. Compare the last value of the first half of the list. If this last value is less than the desired value, search this half of the list. Otherwise, search the other half of the list. 3. Repeat Steps 1 and 2 until the desired value is found or confirmed not to exist. Book IV Chapter 2 Searching Algorithms