Advertisement
borsha06

binary_s

Apr 11th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int a[1000];
  4. int binary(int key,int n)
  5. {
  6.     int ends,beg,index,mid;
  7.     ends=n-1;
  8.     beg=0;
  9.     index= -1;
  10.     while(beg<=ends)
  11.     {
  12.         mid = (beg + ends)/2;
  13.         if(key == a[mid])
  14.         {
  15.             index=mid;
  16.             cout<<index<<endl;
  17.             break;
  18.         }
  19.         else if(key < a[mid])
  20.         {
  21.             ends = mid-1;
  22.             cout<<ends<<endl;
  23.             cout<<index<<endl;
  24.         }
  25.         else if(key > a[mid])
  26.         {
  27.             beg = mid+1;
  28.             cout<<beg<<endl;
  29.             cout<<index<<endl;
  30.         }
  31.  
  32.  
  33.     }
  34.     return index;
  35.  
  36.  
  37. }
  38. int main()
  39. {
  40.     int n,i,j,k,mid,key=23;
  41.     cin>>n;
  42.     for(i=1; i<=n; i++)
  43.     {
  44.         cin>>a[i];
  45.  
  46.     }
  47.     cout<< binary(key,n);
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement