-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Search 1
More file actions
41 lines (41 loc) · 980 Bytes
/
Binary Search 1
File metadata and controls
41 lines (41 loc) · 980 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
//Binary Search
#include <stdio.h>
int search(int a[], int size, int n);
int main()
{
int arr[20], i, size, n, found;
printf("Enetr the total number of elements: ");
scanf("%d", &size);
printf("Enter the %d elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
printf("Enter the numer to be found: ");
scanf("%d", &n);
found=search (arr, size, n);
if (found==-1)
printf("The number %d is not found in the given list", n);
else
printf("The number %d is found in the given list at position %d", n, found+1);
return 0;
}
int search(int a[], int size, int n)
{
int i, l=0, u=size, m, flag=-1;
for (i=0; i<size; i++)
{
while(l<u)
{
m=(l+u)/2;
if(n>a[m])
l=m+1;
else if(n<a[m])
u=m-1;
else
{
flag=m;
break;
}
}
}
return flag;
}