-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbinary_search_recursion.c
More file actions
47 lines (35 loc) · 869 Bytes
/
Copy pathbinary_search_recursion.c
File metadata and controls
47 lines (35 loc) · 869 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
41
42
43
44
45
46
47
#include<stdio.h>
#include<stdlib.h>
#define size 10
int binsearch(int[], int, int, int);
int main() {
int num = 100, i, key, position;
int low, high, list[num];
for (i = 0; i < num; i++) {
list[i] = rand()%100;
}
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);
}
}