fahimkamal63

Binary Search

Oct 18th, 2019
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. //  Binary Search
  2. //  Date : 17.10.19
  3. #include<iostream>
  4. using namespace std;
  5.  
  6. int binarySearch(int arr[], int n, int key){
  7.     int first = 0, last = n-1, mid = (first + last) / 2;
  8.     while(first <= last && arr[mid] != key){
  9.         if(arr[mid] < key){
  10.             first = mid + 1;
  11.         }
  12.         else if(arr[mid] > key){
  13.             last = mid - 1;
  14.         }
  15.         mid = (first + last) / 2;
  16.     }
  17.     if(arr[mid] == key) return mid;
  18.     else return -1;
  19. }
  20.  
  21. int main(){
  22.     int n;
  23.     cout << "Enter the range of array: "; cin >> n;
  24.     int arr[n], i;
  25.     cout << "Enter the element of array: ";
  26.     for(i = 0; i < n; i++){
  27.         cin >> arr[i];
  28.     }
  29.  
  30.     for(i = 0; i < n-1; i++){
  31.         if(arr[i] > arr[i+1]){
  32.             cout << "The array is not sorted and the binary search only works in a sorted array." << endl;
  33.             return 0;
  34.         }
  35.     }
  36.     cout << "Enter the element to search: ";
  37.     int key; cin >> key;
  38.     int isPresent = binarySearch(arr, n, key);
  39.     if(isPresent == -1) cout << "The element is not present" << endl;
  40.     else cout << "The element is present at " << isPresent << " position." << endl;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment