Advertisement
Md_hosen_zisad

binary search

Mar 3rd, 2018
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.     int i,a[100],n,m,low,high,mid;
  6.     cin>>n;
  7.     cout<<"search: ";
  8.     cin>>m;
  9.     low=0,high=n-1;
  10.     cout<<"enter the array: ";
  11.     for(i=0;i<n;i++)
  12.     {
  13.         cin>>a[i];
  14.  
  15.     }
  16.     while(low<=high)
  17.     {
  18.         cout<<"search: ";
  19.         cin>>m;
  20.         mid=(low+high)/2;
  21.         if(m==a[mid])
  22.         {
  23.             break;
  24.         }
  25.         else if(m<a[m])
  26.           {
  27.  
  28.            high=mid-1;}
  29.  
  30.     else if(m>a[m])
  31.     {
  32.         low=mid+1;
  33.     }
  34.     if(low>high)
  35.     cout<<"not found";
  36.     else
  37.         cout<<"found";
  38.  
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement