Skip to content

Commit

Permalink
Binary Search Using Divide and Conquer
Browse files Browse the repository at this point in the history
  • Loading branch information
ranganeeraj authored Oct 1, 2023
1 parent cabb853 commit 18421aa
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions Data Structure/Array Or Vector/Binary Search/SolutionByNeeraj.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <iostream>
#include <ctime>
using namespace std;


int getRandom(int x, int y) {
srand(time(NULL));
return (x + rand() % (y-x+1));
}

int binarySearch(int* arr, int low, int high, int key) {
if (high >= low) {
int mid = getRandom(low, high);
if (arr[mid] == key) {
return mid;
}
if (arr[mid] > key) {
return binarySearch(arr, low, mid-1, key);
}
return binarySearch(arr, mid+1, high, key;
}
return -1;
}

int main() {
int n;
cout << "\nEnter Size\t: ";
cin >> n;
int arr[n];
cout << "\nEnter Elements ";
for(int i =0; i < n; i++ ) {
cin >> arr[i];
}
int key;
cout << "\nEnter key to be search\t: ";
cin >> key;
int temp = binarySearch(arr,0,n-1,key);
if( temp == -1 ) {
cout << "\nKey not Found\n";
}
else {
cout << "\nKey Found at " << temp << " Position\n";
}
return 0;
}

0 comments on commit 18421aa

Please sign in to comment.