Advertisement
skb50bd

Binary Search w/ Recursion

Mar 29th, 2016
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void swap(int &a, int &b) {
  5.     a = a + b;
  6.     b = a - b;
  7.     a = a - b;
  8. }
  9.  
  10. bool binary(int arr[], int n, int SearchItem, int start, int stop) {
  11.     int mid;
  12.     bool found = false;
  13.      if (start <= stop){
  14.           mid = (start + stop) / 2;
  15.           if(SearchItem == arr[mid]) found = true;
  16.           else if(SearchItem < arr[mid]) return binary(arr, n, SearchItem, start, mid - 1);
  17.           else return binary(arr, n, SearchItem, mid + 1, stop);
  18.      }
  19.      else return found;
  20. }
  21.  
  22. int main() {
  23.     int n;
  24.         cout << "Size of the Array: ";
  25.         cin >> n;
  26.  
  27.         int arr[n];
  28.         int SearchItem;
  29.         bool found = false;
  30.         cout << "Enter " << n << " Elements: ";
  31.         for(int i = 0; i < n; i++)
  32.             cin >> arr[i];
  33.  
  34.         //Binary Search
  35.         for(int i = 0; i < n - 1; i++)  //FOR SORTING (SELECTION)
  36.             for(int j = i + 1; j < n; j++)
  37.                 if(arr[i] > arr[j])
  38.                     swap(arr[i], arr[j]);
  39.  
  40.  
  41.         cout << "Enter the value to find (Binary Search): ";
  42.         cin >> SearchItem;
  43.  
  44.         found = binary(arr, n, SearchItem, 0, n - 1);
  45.         if(found) cout << SearchItem << " Found" << endl << endl;
  46.         else cout << SearchItem << " Not Found" << endl << endl;
  47.  
  48.         return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement