-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathbin.c
62 lines (46 loc) · 1.23 KB
/
bin.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
/*
* Program: To perform a binary search
* Author : Abhishek Kadariya [0501]
* BATCH OF 2019 DWIT
*
* Ref : Data structures using C and C++, Chap 2, Page 133
*/
#include<stdio.h>
#include<stdlib.h>
#define size 10
#define loop for (i = 0; i < num; i++)
int binsearch(int [], int, int, int);
int main() {
int num, i, key, position;
int low, high, list[size];
printf("\nEnter the total number of elements");
scanf("%d", &num);
printf("\nEnter the elements of list :");
loop {
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("\nEnter element to be searched : ");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1) {
printf("\nNumber present at %d", (position + 1));
} else
printf("\n The number is not present in the list");
return (0);
}
// Binary Search function
int binsearch(int a[], int x, int low, int high) {
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid]) {
return (mid);
} else if (x < a[mid]) {
binsearch(a, x, low, mid - 1);
} else {
binsearch(a, x, mid + 1, high);
}
}