-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.cpp
62 lines (49 loc) · 1.11 KB
/
day9.cpp
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
59
60
61
62
//linear search and binary search
#include <iostream>
using namespace std;
// Linear search function
int linearSearch(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
// Binary search function
int binarySearch(int arr[], int n, int x) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
// Driver code
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 30;
// Linear search
int index = linearSearch(arr, n, x);
if (index == -1) {
cout << "Element not found" << endl;
} else {
cout << "Element found at index " << index << endl;
}
// Binary search
index = binarySearch(arr, n, x);
if (index == -1) {
cout << "Element not found" << endl;
} else {
cout << "Element found at index " << index << endl;
}
return 0;
}