-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary-search.c
89 lines (82 loc) · 1.52 KB
/
Binary-search.c
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Program to sort an array and find specified element position using binary search algorithm
*/
#include <stdio.h>
void lstp(int n, int *l)
{
int i=0;
for (i=0;i<n;i++)
{
printf("%d ",l[i]);
}
printf("\n");
}
int search(int k, int n, int *arr)
{
int mid, low=0, high=n;
while(1)
{
mid = (low+high)/2;
if (k == arr[mid])
return mid;
else if (mid==low && mid==high)
return -1;
else if (k < arr[mid])
{
high = mid-1;
}
else if (k > arr[mid])
{
low = mid+1;
}
}
}
int main()
{
int n;
printf("Enter the size of array: ");
scanf("%d",&n);
int ar[n];
int i=0,j=0;
for (i=0;i<n;i++)
{
printf("Element %d: ",i+1);
scanf("%d",&ar[i]);
}
for (i=0;i<n;i++)
{
int s = i;
for (j=i+1;j<n;j++)
{
if (ar[j]<ar[s])
{
s=j;
}
}
int t=ar[s];
ar[s]=ar[i];
ar[i]=t;
}
printf("Sorted list is: ");
lstp(n,ar);
printf("Enter the number to be searched: ");
int key;
scanf("%d",&key);
int ind = search(key, n, ar);
if (ind!=-1)
printf("%d found at postion %d",key,ind+1);
else
printf("%d not found in the array.",key);
}
/*
Input:
Enter the size of array: 4
Element 1: 2
Element 2: 5
Element 3: 9
Element 4: 6
Enter the number to be searched: 5
Output:
Sorted list is: 2 5 6 9
5 found at postion 2
*/