-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_search.c
64 lines (62 loc) · 1.3 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
#include <stdio.h>
int binarySearch(int *arr, int size, int ele)
{
int low, high, mid;
low = 0;
high = size - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (arr[mid] == ele)
{
return mid;
}
if (arr[mid] < ele)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
int main()
{
int size;
printf("enter the size of the array :");
scanf("%d", &size);
int arr[size];
printf("enter the %d elements of the array :\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
// Binary search requires the array to be sorted
for (int i = 0; i < size - 1; i++)
{
for (int j = i + 1; j < size; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
int ele;
printf("enter the element to search for: ");
scanf("%d", &ele);
int index = binarySearch(arr, size, ele);
if (index == -1)
{
printf("The element is not present in the array.\n");
}
else
{
printf("The element %d was found at index %d.\n", ele, index);
}
return 0;
}