forked from IEEECS-VIT/selections
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.c
More file actions
40 lines (33 loc) · 831 Bytes
/
BinarySearch.c
File metadata and controls
40 lines (33 loc) · 831 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
#include <stdio.h>
#define MAX 1000
long long int array[MAX];
int main()
{
int current, first, last, middle, num_of_elements, search ;
scanf("%d",&num_of_elements);
for (current = 0; current < num_of_elements; current++)
{
scanf("%d",&array[current]);
}
scanf("%d", &search);
first = 0;
last = num_of_elements - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d is at index %d.\n", search, middle+1);
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if (first > last)
printf("%d is not in the given array\n", search);
return 0;
}