-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbinary.c
More file actions
48 lines (46 loc) · 958 Bytes
/
binary.c
File metadata and controls
48 lines (46 loc) · 958 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
48
#include <stdio.h>
#define max 50
int bin_srch(int a[],int n,int data)
{
int i,l=0,r=n-1;
while(r>=l)
{
int mid=(r+l)/2;
if(data>a[mid])
l=mid+1;
else if(data<a[mid])
r=mid-1;
else
return mid;
}
return -1;
}
int main(){
int a[max],n,data,min,i,j;
printf("Enter the number of items in the array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(i=0;i<n;i++){
min=i;
for(j=i+1;j<n;j++){
if(a[min]>a[j])
min=j;
}
if(min!=i){
int t=a[i];
a[i]=a[min];
a[min]=t;
}
}
printf("Sorted array is: ");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n");
printf("Enter the item to be searched: ");
scanf("%d",&data);
printf("The index is %d",1+bin_srch(a,n,data));
}