forked from shivaylamba/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch Implementation
53 lines (51 loc) · 845 Bytes
/
BinarySearch Implementation
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
49
50
51
#include<stdio.h>
int main()
{
//BinarySearch
int a[50],n,i,j,temp,high,low,mid,q,loc=0;
//clrscr();
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter elements of array:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
//Sorting
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Sorted array: \n[");
for(i=0;i<n;i++)
printf("%5d",a[i]);
printf(" ]\n");
//Search
printf("Enter element to be searched: ");
scanf("%d",&q);
high=n-1;
low=0;
mid=(low+high)/2;
while((low<=high)&&(a[mid]!=q))
{
if(q>a[mid])
low=(mid+1);
else
high=(mid-1);
mid=(low+high)/2;
}
if(q==a[mid])
{
loc=mid+1;
printf("\nSearch successful.\nElement %d found at %d position.",q,loc);
}
else
printf("\nSearch Unsuccessful.");
return 0;
}