Design and Analysis - Binary Search



Binary search method is a searching algorithm that follows the divide and conquer technique. This is based on the idea of ordered searching where the algorithm divides the sorted list into two halves and performs the searching. If the key value to be searched is lower than the mid-point value of the sorted list, it performs searching on the left half; otherwise it searches the right half. If the array is unsorted, linear search is used to determine the position.

Binary Search Algorithm

In this algorithm, we want to find whether element x belongs to a set of numbers stored in an array numbers[]. Where l and r represent the left and right index of a sub-array in which searching operation should be performed.

Algorithm: Binary-Search(numbers[], x, l, r)
   if l = r then
      return l
   else
      m := $\lfloor (l + r) / 2\rfloor$
   if x ≤ numbers[m] then
      return Binary-Search(numbers[], x, l, m)
   else
      return Binary-Search(numbers[], x, m+1, r)

Example

In this example, we are going to search element 63.

binary search

Analysis

Linear search runs in O(n) time. Whereas binary search produces the result in O(log n) time.

Let T(n) be the number of comparisons in worst-case in an array of n elements.

Hence,

$$T\left ( n \right )=\left\{\begin{matrix} 0 & if\: n=1\\ T\left ( \frac{n}{2} \right )+1 & otherwise \\ \end{matrix}\right.$$

Using this recurrence relation T(n)=log n.

Therefore, binary search uses O(log n) time.

Example

In the following implementation, we are trying to search for an integer value from a list of values by applying the bianry search algorithm.

#include<stdio.h>
int binarySearch(int arr[], int p, int r, int num){
   if (p <= r) {
      int mid = (p + r)/2;
      if (arr[mid] == num)
         return mid ;
      if (arr[mid] > num)
         return binarySearch(arr, p, mid-1, num);
      if (arr[mid] < num)
         return binarySearch(arr, mid+1, r, num);
   }
   return -1;
}
int main(){
   int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
   int n = sizeof(arr)/ sizeof(arr[0]);
   printf("Array elements are: \n");
   for(int i = 0; i<n; i++){
       printf("%d ", arr[i]);
   }
   printf("\n");
   int num = 15;
   int index = binarySearch (arr, 0, n-1, num);
   if(index == -1) {
      printf("%d is not found in the array", num);
   } else {
      printf("%d is found at index %d in the array", num, index);
   }
   return 0;
 }

Output

Array elements are: 
1 3 7 15 18 20 25 33 36 40 
15 is found at index 3 in the array
#include<iostream>
using namespace std;
int binarySearch(int arr[], int p, int r, int num){
   if (p <= r) {
      int mid = (p + r)/2;
      if (arr[mid] == num)
         return mid ;
      if (arr[mid] > num)
         return binarySearch(arr, p, mid-1, num);
      if (arr[mid] < num)
         return binarySearch(arr, mid+1, r, num);
   }
   return -1;
}
int main(){
   int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
   int n = sizeof(arr)/ sizeof(arr[0]);
   cout<<"Array elements are: "<<endl;
   for(int i = 0; i<n; i++){
       cout<<arr[i]<<" ";
   }
   cout<<"\n";
   int num = 15;
   int index = binarySearch (arr, 0, n-1, num);
   if(index == -1) {
      cout<< num <<" is not found in the array";
   } else {
      cout<< num <<" is found at index "<< index <<" in the array";
   }
   return 0;
 }

Output

Array elements are: 
1 3 7 15 18 20 25 33 36 40 
15 is found at index 3 in the array
public class Binary_Search {
   public static int binarySearch(int arr[], int low, int high, int key) {
      int mid = (low + high)/2;
      while( low <= high ) {
         if ( arr[mid] < key ) {
            low = mid + 1;
         } else if ( arr[mid] == key ) {
            return mid;
         } else {
            high = mid - 1;
         }
         mid = (low + high)/2;
      }
      return -1;
   }
   public static void main(String args[]) {
      int[] arr = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
      System.out.println("Array elements are: ");
      for(int i = 0; i<arr.length; i++){
          System.out.print(arr[i] + " ");
      }
      System.out.println("");
      int key = 15;
      int high=arr.length-1;
      int i = binarySearch(arr,0,high,key);
      if (i != -1) {
         System.out.println(key + " is found at index " + i + " in the array");
      } else {
         System.out.println(key + " is not found in the array1");
      }
   }
}

Output

Array elements are: 
1 3 7 15 18 20 25 33 36 40 
15 is found at index 3 in the array
def binarySearch(arr, low, high, key):
   mid = (low + high)//2
   while( low <= high ):
      if ( arr[mid] < key ):
         low = mid + 1
      elif ( arr[mid] == key ):
         return mid
      else:
         high = mid - 1
      mid = (low + high)//2
   return -1;

arr = [1, 3, 7, 15, 18, 20, 25, 33, 36, 40]
print("Array elements are: ")
print(arr)
key = 15
high=len(arr)-1
i = binarySearch(arr,0,high,key)
if (i != -1):
   print(key , "is found at index" , i , "in the array")
else:
   print("key is not found in the array")

Output

Array elements are: 
[1, 3, 7, 15, 18, 20, 25, 33, 36, 40]
15 is found at index 3 in the array
Advertisements