forked from suman-shah/c-program-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.c
36 lines (34 loc) · 832 Bytes
/
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
#include<stdio.h>
int binary_search(int arr[],int n,int x){
int start = 0;
int end = n-1;
while(start<=end){
int mid = (start+end)/2;
if(arr[mid]==x)
return mid;
else if(arr[mid]<x)
start = mid + 1;
else
end = mid - 1;
}
return -1;
}
int main()
{
int n, arr[n],i;
scanf("%d",&n);
for (i=0;i<n;i++){
scanf("%d",&arr[i]);
}
int x;
printf("Enter element you want to search: ");
scanf("%d",&x);
int index = binary_search(arr,n,x);
if(index!=-1){
printf("%d%s%d",x," is present at index ",index);
}
else{
printf("%d%s",x," is not present in the given array\n");
}
return 0;
}