-
Notifications
You must be signed in to change notification settings - Fork 0
/
142.cpp
48 lines (48 loc) · 1000 Bytes
/
142.cpp
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
// Recursive method
#include <stdio.h>
#include <stdlib.h>
int binarysearch(int a[], int key, int low, int high)
{
if (low > high)
{
return -1;
}
int mid = (low + high) / 2;
if (a[mid] == key)
{
return mid;
}
if (key > a[mid])
{
return binarysearch(a, key, mid + 1, high);
}
else
{
return binarysearch(a, key, low, mid - 1);
}
}
int main()
{
int n, key;
printf("Enter the number of element:");
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int));
printf("Enter the element:");
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the key:");
scanf("%d", &key);
int res;
res = binarysearch(a, key, 0, n - 1);
if (res != -1)
{
printf("Yes %d is present at %d postion", key, (res + 1));
}
else
{
printf("%d not found in the array !!", key);
}
return 0;
}