Advertisement
alaminrifat

Binary Search in C++

Oct 12th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.62 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6.     int arrSize = 10;
  7.     int arr[arrSize]= {6,10,22,37,42,55,63,71,88,92};
  8.  
  9.     cout<<"Enter Number you want to search :: ";
  10.     int n ;
  11.     cin >>n;
  12.  
  13.     int left = 0,middle;
  14.     int right = arrSize;
  15.  
  16.     while(left<=right)
  17.     {
  18.         middle = (left+right)/2;
  19.  
  20.         if(arr[middle]==n)
  21.         {
  22.             cout<<"Item found at index "<<middle<<endl;
  23.             break;
  24.         }
  25.         else if (arr[middle]<n)
  26.         {
  27.             left = middle + 1;
  28.         }
  29.         else
  30.         {
  31.             right = middle - 1;
  32.         }
  33.     }
  34.  
  35.  
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement