Advertisement
SabirSazzad

Binary Search

Feb 26th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. int Binary_Search (int n,int num[],int newValue);
  4. int main()
  5. {
  6.     int n,i,newValue,result;
  7.     cout << "Enter Array Size: ";
  8.     cin >> n;
  9.     int num[n];
  10.     cout << "Enter Values....." <<endl;
  11.     for(i=0; i<n; i++)
  12.     {
  13.         cin >> num[i];
  14.     }
  15.     cout << "Input a Number to search: ";
  16.     cin >> newValue;
  17.     result = Binary_Search(n,num,newValue);
  18.     if(result==-5)
  19.     {
  20.         cout << "Not Found" <<endl;
  21.     }
  22.     else
  23.     {
  24.         cout << "Found at Index " << result;
  25.     }
  26.     return 0;
  27. }
  28.  
  29. int Binary_Search (int n, int num[],int newValue)
  30. {
  31.     int last,first=0,mid;
  32.     last = n-1;
  33.     while(first <= last)
  34.     {
  35.         mid = (first+last)/2;
  36.         if(num[mid] == newValue)
  37.         {
  38.             return mid;
  39.         }
  40.         else if(newValue > num[mid])
  41.         {
  42.             first = mid + 1;
  43.         }
  44.         else
  45.         {
  46.             last = mid - 1;
  47.         }
  48.     }
  49.  
  50.     return -5;
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement