Advertisement
Guest User

Untitled

a guest
Apr 26th, 2015
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int Sort(int *ar, int s)
  6. {
  7.     int i, j;
  8.  
  9.     for( i =0; i<s-1; i++)
  10.         for(j =i+1; j<s; j++)
  11.         {
  12.             if(ar[i]>ar[j])
  13.             {
  14.                 int temp = ar[i];
  15.                 ar[i] = ar[j];
  16.                 ar[j] = temp;
  17.             }
  18.         }
  19. }
  20.  
  21.  int binarysearch(int *ar,int s,int key)
  22.  {
  23.     int st =0, e = s,mid;
  24.     while(st<=e)
  25.     {
  26.        mid = (st+e)/2;
  27.        if(ar[mid]<key)
  28.        {
  29.            st = mid+1;
  30.        }
  31.        else if(ar[mid]>key)
  32.        {
  33.            e = mid-1;
  34.        }
  35.        else if (st>e)
  36.        {
  37.           // cout<<st<<" "<<e<<endl;
  38.            return -1;
  39.        }
  40.        else if (ar[mid] == key)
  41.        {
  42.            //cout<<"mid in equal = "<<mid<<endl;
  43.            return mid;
  44.        }
  45.     }
  46. }
  47.  
  48.  
  49. int main(){
  50.  
  51.   int ar[100],s,key, f;
  52.   cout<<"give size of array\n";
  53.   cin>>s;
  54.  
  55.   for(int i =0; i<s; i++)
  56.   {
  57.       cin>>ar[i];
  58.   }
  59.  
  60.   Sort(ar,s);
  61.  
  62.   for(int i =0; i<s; i++)
  63.   {
  64.       cout<<ar[i]<<" ";
  65.   }
  66.  
  67.   cout<<"enter key\n";
  68.  
  69.  
  70.       cin>>key;
  71.  
  72.  
  73.    // int st =0, e = s,mid, f = 0;
  74.   /*  while(st <= e)
  75.     {
  76.        mid = (st+e)/2;
  77.        if(ar[mid]<key)
  78.           st = mid+1;
  79.  
  80.        else if(ar[mid]>key)
  81.            e = mid-1;
  82.  
  83.        else if (st>e)
  84.            break;
  85.  
  86.        else if (ar[mid] == key)
  87.        {
  88.            cout<<"mid in equal = "<<mid<<endl;
  89.            f = 1;
  90.            break;
  91.        }
  92.     }
  93.     */
  94.     f = binarysearch(ar,s,key);
  95.  
  96.     cout<<f<<endl;
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement