forked from CodeToExpress/dailycodebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.c
58 lines (42 loc) · 968 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
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* @author : ashwek
* @date : 29/01/2019
*/
#include <stdio.h>
#include <stdlib.h>
int binary_search(int *arr, int n, int search){
int low = 0, high = n-1;
int mid;
while( low <= high ){
mid = (high - low) / 2 + low;
if( arr[mid] == search ){
return mid;
}
else if( search < arr[mid] ){
high--;
}
else{
low++;
}
}
return -1;
}
void main(){
int *arr, n, search, i;
printf("Enter size of array = ");
scanf("%d", &n);
arr = (int *)malloc(sizeof(int)*n);
printf("Enter %d elements (in sorted order) : ", n);
for(i=0; i<n; i++){
scanf("%d", &arr[i]);
}
printf("Enter a value to search = ");
scanf("%d", &search);
i = binary_search(arr, n, search);
if( i == -1 ){
printf("%d not found in array", search);
}
else{
printf("%d found at %d index", search, i);
}
}