-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.c
65 lines (61 loc) · 1.04 KB
/
binary_search.c
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
63
64
65
#include <stdio.h>
void scan_arr(int *arr, int size)
{
printf("Enter array elements :\n");
for (int i =0; i < size ; i++)
{
scanf("%d",&arr[i]);
}
}
void print_arr(int *arr, int size)
{
printf("Index : ");
for (int i =0; i < size ; i++)
{
printf("[%d]\t",i);
}
printf("\n");
printf("Element: ");
for (int i =0; i < size ; i++)
{
printf("%d \t ", arr[i]);
}
printf("\n");
}
int main()
{
int arr[100], low , high , mid, flag =0;
int key, size, index;
printf("Enter sorted array size:");
scanf("%d", &size);
scan_arr(arr, size);
print_arr(arr, size);
printf("Enter element to search :");
scanf("%d", &key);
low = 0;
high = size-1;
while( low <= high )
{
mid = (low+high)/2;
if ( key == arr[mid] )
{
index = mid;
flag = 1;
break;
}
else if (arr[mid] > key)
{
high = mid-1;
}
else if (arr[mid] < key)
{
low = mid + 1;
}
}
if (flag)
printf("Element found at index : %d\n", index);
else
{
printf("Requested element not found in the given array.\n", key);
}
}