Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- void swap(int &a, int &b) {
- a = a + b;
- b = a - b;
- a = a - b;
- }
- bool binary(int arr[], int n, int SearchItem, int start, int stop) {
- int mid;
- bool found = false;
- if (start <= stop){
- mid = (start + stop) / 2;
- if(SearchItem == arr[mid]) found = true;
- else if(SearchItem < arr[mid]) return binary(arr, n, SearchItem, start, mid - 1);
- else return binary(arr, n, SearchItem, mid + 1, stop);
- }
- else return found;
- }
- int main() {
- int n;
- cout << "Size of the Array: ";
- cin >> n;
- int arr[n];
- int SearchItem;
- bool found = false;
- cout << "Enter " << n << " Elements: ";
- for(int i = 0; i < n; i++)
- cin >> arr[i];
- //Binary Search
- for(int i = 0; i < n - 1; i++) //FOR SORTING (SELECTION)
- for(int j = i + 1; j < n; j++)
- if(arr[i] > arr[j])
- swap(arr[i], arr[j]);
- cout << "Enter the value to find (Binary Search): ";
- cin >> SearchItem;
- found = binary(arr, n, SearchItem, 0, n - 1);
- if(found) cout << SearchItem << " Found" << endl << endl;
- else cout << SearchItem << " Not Found" << endl << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement