Ch 2 - Lists - Part 2 (Updated) (2)
Ch 2 - Lists - Part 2 (Updated) (2)
Data Structures
For this algorithm to work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middlemost item of
the collection.
If a match occurs, then the index of the item is returned.
If the middle item is greater than the item, then the item is searched in the sub-array
to the left of the middle item.
Otherwise, the item is searched for in the sub-array to the right of the middle item.
This process continues on the sub-array as well until the size of the subarray reduces
to
zero.
Note that for a binary search to work, it is mandatory for the target array to be
sorted
The following is our sorted array and let us assume that we need to search
the location of value 31 using binary search.
Now we compare the value stored at location 4, with the value being searched, i.e.
31. We find that the value at location 4 is 27, which is not a match.
As the value is greater than 27 and we have a sorted array, so we also know that the
target value must be in the upper portion of the array.
As the value is greater than 27 and we have a sorted array, so we also know that
the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1;
mid = (high + low) / 2;
Our new mid is 7 now. We compare the value stored at location 7 with our
target value of 31.
The value stored at location 7 is not a match, rather it is less than what
we are looking for. So, the value must be in the lower part of this
location.
Hence, we change our high and the new mid using. New mid will be
5 high = mid - 1;
mid = (high + low) / 2;
We compare the value stored at location 5 with our target value. We find
that
it is a match.
13
Faculty of Information Technology - Computer Science Department