Skip to content

Commit 18421aa

Browse files
authored
Binary Search Using Divide and Conquer
1 parent cabb853 commit 18421aa

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <iostream>
2+
#include <ctime>
3+
using namespace std;
4+
5+
6+
int getRandom(int x, int y) {
7+
srand(time(NULL));
8+
return (x + rand() % (y-x+1));
9+
}
10+
11+
int binarySearch(int* arr, int low, int high, int key) {
12+
if (high >= low) {
13+
int mid = getRandom(low, high);
14+
if (arr[mid] == key) {
15+
return mid;
16+
}
17+
if (arr[mid] > key) {
18+
return binarySearch(arr, low, mid-1, key);
19+
}
20+
return binarySearch(arr, mid+1, high, key;
21+
}
22+
return -1;
23+
}
24+
25+
int main() {
26+
int n;
27+
cout << "\nEnter Size\t: ";
28+
cin >> n;
29+
int arr[n];
30+
cout << "\nEnter Elements ";
31+
for(int i =0; i < n; i++ ) {
32+
cin >> arr[i];
33+
}
34+
int key;
35+
cout << "\nEnter key to be search\t: ";
36+
cin >> key;
37+
int temp = binarySearch(arr,0,n-1,key);
38+
if( temp == -1 ) {
39+
cout << "\nKey not Found\n";
40+
}
41+
else {
42+
cout << "\nKey Found at " << temp << " Position\n";
43+
}
44+
return 0;
45+
}

0 commit comments

Comments
 (0)