-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.c
More file actions
39 lines (28 loc) · 934 Bytes
/
binarysearch.c
File metadata and controls
39 lines (28 loc) · 934 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
#include <stdio.h>
int main() {
int n,x,arr[10],i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter %d elements in sorted order:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the target element to search: ");
scanf("%d", &x);
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2; // Calculate mid directly
if (arr[mid] == x) {
printf("Element found at index %d.\n", mid + 1); // 1-based index
return 0; // Exit the program as we found the target
}
if (arr[mid] < x) {
left = mid + 1; // Adjust left boundary
} else {
right = mid - 1; // Adjust right boundary
}
}
// If we exit the loop without finding the element
printf("Element not found in the array.\n");
return 0;
}