Searching is a task closely related to sorting. The basic idea is to quickly locate a specific value in an array or determine that the array doesn't contain the value. Although searching for a particular value in an array of simple data (e.g., characters or integers) has limited use, doing so is a good example of a searching algorithm. Searching for a specific element becomes more useful when the elements are objects, instances of structures, or classes.
Imagine that we begin with a student structure that has three fields or members: (1) the student's name, (2) the student's identification number, and (3) the student's GPA. Next, we create an array of objects instantiated from the structure and initialize all fields in each object. Now, we can search for a specific student's ID; if we find that ID, the search also returns the student's name and GPA. This operation is called an associative search, and the structure field used for the search, ID in this example, is called the key.
Binary search is a simple but effective searching algorithm often used with arrays. However, it has one requirement: we must sort the array before we can apply the binary search algorithm. The basic operation is to divide the array in half and ask, "Is the element I'm looking for in the top or bottom half?" Ignore the half of the array that doesn't contain the element, and then repeat the process until the algorithm locates the correct element or determines that the element is not in the array. The binary search doesn't change the array; instead, it performs its operations through three variables that index into the array.
(a)
(b)
(c)
(d)
(e)
Binary search. The binary search algorithm divides an array into two sub-arrays, determines if the key or target element is in the upper or lower sub-array, and then repeats. At some point, the sub-array is small enough that the key's location is determined or that the key is not in the array. The algorithm performs all partitioning steps (dividing the array into sub-arrays) through three index variables:
top: the index location of the top of the current sub-array
mid: the index location of the middle of the current sub-array
bottom: the index location of the bottom of the current sub-array
Illustrated are the steps binary search takes to locate 'Q' (the key or target) in a simple array of characters:
The original, unsorted array.
The array is sorted, top and bottom are initialized, and the first value of mid is calculated.
The key is in the bottom half of the array, so the algorithm updates top and calculates a new value for mid.
The key is in the top half of the array, so the algorithm updates bottom and calculates a new value for mid.
In this specific example, all three indexes are equal; it is not a requirement that top and bottom point to the key, only that mid does.