Searching and sorting algorithms - AQABinary search

Sorting and searching are two of the most frequently needed algorithms in program design. These algorithms have evolved to take account of this need.

Part ofComputer ScienceComputational thinking and problem solving

Binary search

Another example of a computer searching is binary search. This is a more complex algorithm than and requires all items to be in order.

With each that is run, half of the is removed from the search. To do this, the algorithm uses the of items in the list - an index is the number given to the position of an item in a list.

To determine the next item to be checked in a list, the midpoint has to be identified. This is found by adding the lowest index to the highest index and dividing by two, then rounding either up or down to the nearest if needed. Whether we round up or down does not matter, as long as within a particular search the same method is applied. For example, if the highest index in a list is 8 and the lowest is 0, the midpoint can be found using the following sum:

Highest index (8) + lowest index (0) = 8

8/2 = 4

The algorithm runs as follows:

  1. Start by setting the counter to the middle position in the list.
  2. If the value held there is a match, the search ends.
  3. If the value at the midpoint is less than the value to be found, the list is divided in half, the lower half of the list is ignored and the search keeps to the upper half of the list.
  4. Otherwise, if the value at the midpoint is greater than the value to be found, the upper half of the list is ignored and the search keeps to the lower half of the list.
  5. The search moves to the midpoint of the remaining items. Steps 2 through 4 continue until a match is made or there are no more items to be found.

Binary search example

This algorithm could be used to search the following list for the number 7:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

In a , this would look like:

Search termStartEndMidFoundList
71105False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
6108False[6, 7, 8, 9, 10]
676False[6, 7]
777True[7]
Search term7
Start1
End10
Mid5
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Start6
End10
Mid8
FoundFalse
List[6, 7, 8, 9, 10]
Search term
Start6
End7
Mid6
FoundFalse
List[6, 7]
Search term
Start7
End7
Mid7
FoundTrue
List[7]

In , this would look like:

Find <-- 7
Found <-- False
Start <-- 0
End <-- length(list) WHILE Found = False AND Start <= End Mid <-- (Start + End) DIV 2 IF list[Mid] = Find THEN OUTPUT 'Found at' + Mid Found <-- True ELSE IF List[Mid] > Find THEN End <-- Mid - 1 ELSE Start <-- Mid + 1 ENDIF ENDIF
ENDWHILE IF Found = False THEN OUTPUT 'Not found'
ENDIF

Searching a data set using binary search