forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search.c
45 lines (43 loc) · 943 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
37
38
39
40
41
42
43
44
45
#include <stdio.h>
#include<stdlib.h>
int binary_search(int a[],int beg,int end,int c);
int main(){
int n;
printf("Enter the length of list : ");
scanf("%d",&n);
int arr[n];
printf("Enter the elements of list : ");
for(int i=1;i<=n;i++){
scanf("%d",&arr[i]);
}
int item;
printf("enter the element you want to search : ");
scanf("%d",&item);
int pos;
int strt=1;
pos=binary_search(arr,strt,n,item);
printf("%d",pos);
if(pos==-1){
printf("search unsuccesful .;");
}
else{
printf("the element is on %d location of array",pos);
}
return 0;
}
int binary_search(int a[],int beg,int end,int c){
int mid;
while(beg<=end){
mid=(end+beg)/2;
if(a[mid] == c){
return mid;
}
else if(a[mid]< c){
beg=mid+1;
}
else{
end=mid-1;
}
}
return -1;
}