19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

192 <strong>Computer</strong> <strong>Programming</strong> <strong>Concepts</strong> <strong>and</strong> <strong>Visual</strong> <strong>Basic</strong><br />

whose name begins with “A” rather quickly, but 1000 comparisons might be necessary to find<br />

a person whose name begins with “Z.” For much longer lists, searching could be a time-consuming<br />

matter. However, when the list has already been sorted into either ascending or descending<br />

order, there is a method, called a binary search, that shortens the task considerably.<br />

Let us refer to the sought item as quarry. The binary search looks for quarry by determining<br />

in which half of the list it lies. The other half is then discarded, <strong>and</strong> the retained half<br />

is temporarily regarded as the entire list. The process is repeated until the item is found. A<br />

flag can indicate if quarry has been found.<br />

The algorithm for a binary search of an ascending list is as follows (Figure 6-8 shows<br />

the flowchart for a binary search):<br />

1. At each stage, denote the subscript of the first item in the retained list by first<br />

<strong>and</strong> the subscript of the last item by last. Initially, the value of first is 1, the<br />

value of last is the number of items in the list, <strong>and</strong> the value of flag is False.<br />

2. Look at the middle item of the current list, the item having the subscript middle<br />

= Int((first + last) / 2).<br />

3. If the middle item is quarry, then flag is set to True <strong>and</strong> the search is over.<br />

4. If the middle item is greater than quarry, then quarry should be in the first half<br />

of the list. So the subscript of quarry must lie between first <strong>and</strong> middle [minus]<br />

1. That is, the new value of last is middle – 1.<br />

5. If the middle item is less than quarry, then quarry should be in the second half<br />

of the list of possible items. So the subscript of quarry must lie between middle<br />

+ 1 <strong>and</strong> last. That is, the new value of first is middle + 1.<br />

6. Repeat Steps 2 through 5 until quarry is found or until the halving process uses<br />

up the entire list. (When the entire list has been used up, first > last.) In the second<br />

case, quarry was not in the original list.<br />

FIGURE 6-8 Flowchart for a Binary Search

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

Saved successfully!

Ooh no, something went wrong!