-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode for the Binary search
More file actions
33 lines (31 loc) · 862 Bytes
/
Copy pathCode for the Binary search
File metadata and controls
33 lines (31 loc) · 862 Bytes
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
//https://www.facebook.com/permalink.php?story_fbid=2376635879298242&id=100008555587566
//Subscribed and liked by Aryan kumar
#include<stdio.h>
int binarySearch(int arr[], int size, int element){
int low, mid, high;
low = 0;
high = size-1;
// Keep searching until low <= high
while(low<=high){
mid = (low + high)/2;
if(arr[mid] == element){
return mid;
}
if(arr[mid]<element){
low = mid+1;
}
else{
high = mid -1;
}
}
return -1;
}
int main(){
// Sorted array for binary search
int arr[] = {1,3,5,56,64,73,123,225,444};
int size = sizeof(arr)/sizeof(int);
int element = 444;
int searchIndex = binarySearch(arr, size, element);
printf("The element %d was found at index %d \n", element, searchIndex);
return 0;
}