Skip to content

Commit

Permalink
Merge pull request #1922 from ranganeeraj/patch-10
Browse files Browse the repository at this point in the history
Binary Search Using Divide and Conquer
  • Loading branch information
shoaibrayeen authored Oct 2, 2023
2 parents 00fb06a + 18421aa commit ea6d085
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 ea6d085

Please sign in to comment.