Advertisement
ruhan008

Binary Search program

Nov 8th, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. // 2) WAP to implement binary search
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int main(){
  6.    
  7.     cout<<"Enter the size of the sorted array: ";
  8.     int n;
  9.     cin>>n;
  10.     int arr[n];
  11.     cout<<"Enter the array elements: ";
  12.     for(int i=0;i<n;i++) {
  13.         cin>>arr[i];
  14.     }
  15.  
  16.     cout<<"Enter the element to be searched: ";
  17.     int element;
  18.     cin>>element;
  19.     int index=-1;
  20.     int low=0,high=n-1;
  21.     while(low<=high){
  22.         int mid=(low+high)/2;
  23.         if(arr[mid]==element){
  24.             index=mid;
  25.             break;
  26.         }
  27.         else if(arr[mid]>element) high=mid-1;
  28.         else low=mid+1;
  29.     }
  30.  
  31.     if(index!=-1){
  32.         cout<<"Element found at index: "<<index<<endl;
  33.     }
  34.     else cout<<"Element not found!!!"<<endl;
  35.  
  36.    
  37.     return 0;
  38. }
  39. /*
  40.     OUTPUT:
  41.     Enter the size of the sorted array: 5
  42.     Enter the array elements: 4 5 10 12 33
  43.     Enter the element to be searched: 4
  44.     Element found at index: 0
  45. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement