-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDS7.C
More file actions
44 lines (34 loc) · 983 Bytes
/
Copy pathDS7.C
File metadata and controls
44 lines (34 loc) · 983 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
//Data Structure Program 7
//Binary Search
#include <stdio.h>
#include<stdlib.h>
#include<conio.h>
int binarysearch(int a[], int low, int high, int x) {
int mid = (low + high) / 2;
if (low > high) return -1;
if (a[mid] == x) return mid;
if (a[mid] < x)
return binarysearch(a, mid + 1, high, x);
else
return binarysearch(a, low, mid-1, x);
}
int main(void) {
int a[100];
int len, pos, search_item,i;
system("cls");
printf("Enter the length of the array\n");
scanf("%d", &len);
printf("Enter the array elements\n");
for (i=0; i<len; i++)
scanf("%d", &a[i]);
printf("Enter the element to search\n");
scanf("%d", &search_item);
pos = binarysearch(a,0,len-1,search_item);
if (pos < 0 )
{ printf("Cannot find the element %d in the array.\n", search_item);
getch();}
else
{ printf("The position of %d in the array is %d.\n", search_item, pos+1);
getch();}
return 0;
}