Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Binary search
Binary Search is a Divide and Conquer algorithm. Like all divide and conquer algorithms,
Binary Search first divides a large array into two smaller sub-arrays and then recursively
(or iteratively) operate the sub-arrays. But instead of operating on both sub-arrays, it
discards one sub-array and continue on the second sub-array. This decision of discarding
one sub-array is made in just one comparison.
So Binary Search basically reduces the search space to half at each step. By search
space we mean sub-array of given array where the target value is located (if present in
the array). Initially, the search space is the entire array and binary search redefine the
search space at every step of the algorithm by using the property of the array that it is
sorted. It does so by comparing the mid value in the search space to the target value. If
the target value matches the middle element, its position in the array is returned else it
discards half of the search space based on the comparison result.
Binary search
Suppose we have a sequence of array A with n elements that has been sorted to
increasing order. Now suppose we must search whether a key k occurs in A .
In the latter two cases, we recursively continue in the selected half of the sequence until
either
For example, below we display the steps of binary search for the key 20 in the ordered
sequence [4,5,10,15,20,25,35,40,45,50,58,65,80,98]. In each step, we highlight with
blue the current subsequence defined by the indices low and high:
Analysis:
Derivation->
=> n/2^k= 1 [So how many times we need to divide by 2 until we have only one element
left]
=> n=2^k
T(n) = 1 + log n [we know that T(1) = 1 , because it’s a base condition as we are left with
only one element in the array and that is the element to be searched so we return 1]