Advertisement
Rakibul_Ahasan

Binary Search

Oct 14th, 2019
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int Binary_search(int A[],int n,int item)
  5. {
  6.     int first=0,last=n-1;
  7.  
  8.     while(first<=last)
  9.     {
  10.         int mid=(first+last)/2;
  11.  
  12.         if(A[mid]==item)
  13.         {
  14.             return mid;
  15.         }
  16.         else if(A[mid]>item)
  17.         {
  18.             last=mid-1;
  19.         }
  20.         else if(A[mid]<item)
  21.         {
  22.             first=mid+1;
  23.         }
  24.     }
  25.     return -1;
  26. }
  27.  
  28. int main()
  29. {
  30.     int n,item;
  31.     cin>>n;
  32.     int arr[n];
  33.  
  34.     for(int i=0;i<n;i++){
  35.         cin>>arr[i];
  36.     }
  37.     cin>>item;
  38.  
  39.     int loc=Binary_search(arr,n,item);
  40.  
  41.     if(loc==-1){
  42.         cout<<"Element is not present in array"<<endl;
  43.     }
  44.     else cout<<"Element is present at index "<<loc+1<<endl;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement