-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathBinary Search.c
52 lines (49 loc) · 1.09 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
// BINARY SEARCH
#include <stdio.h>
int BinarySearch(int array[], int length, int key)
{
int high = length - 1;
int low = 0;
if (low <= high)
{
while (low <= high)
{
int mid = (low + high) / 2;
if (key == array[mid])
{
return mid;
}
else if (key < array[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
}
return -1;
}
int main()
{
int n, i, item;
printf("\nEnter the no of array elements: ");
scanf("%d", &n);
int a[n];
printf("\nEnter the array elements: ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\nEnter the item to be searched: ");
scanf("%d", &item);
int result = BinarySearch(a, n, item);
if (result == -1)
{
printf("\nElement is not present in the array\n");
}
else
{
printf("\nElement is found at index: %d\n", result);
}
return 0;
}