-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
58 lines (55 loc) · 1.53 KB
/
Copy pathBinarySearch.cpp
File metadata and controls
58 lines (55 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <bits/stdc++.h>
using namespace std;
int binarysearch(int arr[], int key, int low, int high) {
while (low <= high) {
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
else if (key < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
int binarysearchR(int arr[], int key, int low, int high) {
if (low <= high) {
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
else if (key < arr[mid]) {
return binarysearchR(arr, key, low, mid - 1);
} else {
return binarysearchR(arr, key, mid + 1, high);
}
}
return -1;
}
int main() {
int num;
cout << "Enter the Number of Elements: ";
cin >> num;
int arr[num];
for (int i = 0; i < num; i++) {
cin>> arr[i];
}
for (int i = 0; i < num; i++) {
for (int j = i + 1; j < num; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
cout << "\nSorted Array is: \n";
for (int i = 0; i < num; i++) {
cout << arr[i] << " ";
}
int key;
cout << "\n\nEnter the Key Element: ";
cin >> key;
cout << "\nIterative Binary Search Element Found At " << binarysearch(arr, key, 0, num - 1);
cout << "\nRecursive Binary Search Element Found At " << binarysearchR(arr, key, 0, num - 1);
}