Binary Search

PHOTO EMBED

Tue Jan 11 2022 16:05:38 GMT+0000 (UTC)

Saved by @yaminisingh #c++

#include<bits/stdc++.c>

int binarysearch(int arr[], int l, int r, int x){
  if(r>=l){
     int mid= l+(r-1)/2;
     if(arr[mid]== x){
       return mid;
     }
    if(x<arr[mid]){
      return binarysearch(arr, l ,mid-1, x);
    }
    if(x>arr[mid]){
      return binarysearch(arr, mid+1, r, x);
    }
  }
  return -1;
  
}

int main(){
  int arr[]= {10, 20, 30, 40, 50};
  int x= 30;
  int n= sizeof(arr)/ sizeof(arr[0]);
  int result= binarysearch(arr, 0, 1, n-1m, x);
  (result==-1)? cout<<"Element is not present" : cout<<"Element is present at"<<result;
  return 0;
  
}
content_copyCOPY

Binary search divides the array into 2 halves, one smaller than the index and one with the elements greater than the index. The value is then searched in one of the halves and value is searched after recurrence.

https://www.geeksforgeeks.org/binary-search/