-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinearsearch.cpp
More file actions
44 lines (34 loc) · 922 Bytes
/
linearsearch.cpp
File metadata and controls
44 lines (34 loc) · 922 Bytes
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
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int key) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid; // element found
else if (arr[mid] < key)
low = mid + 1; // search right half
else
high = mid - 1; // search left half
}
return -1; // element not found
}
int main() {
int n, key;
cout << "Enter number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements in sorted order:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter element to search: ";
cin >> key;
int result = binarySearch(arr, n, key);
if (result != -1)
cout << "Element found at index " << result << endl;
else
cout << "Element not found!" << endl;
return 0;
}