Skip to content

Instantly share code, notes, and snippets.

@sujaykundu777
Created July 25, 2017 04:15
Show Gist options
  • Save sujaykundu777/59b1d5a80957b225c00cad34941089fa to your computer and use it in GitHub Desktop.
Save sujaykundu777/59b1d5a80957b225c00cad34941089fa to your computer and use it in GitHub Desktop.
Binary Search in C
#include<stdio.h>
#define max_size 1000 //Maximum size ot the Array
int main(){
int arr[max_size];
int arr_size,i;
int key;
int lowerbound;
int upperbound;
int midPoint;
int result = -1;
printf("Enter the Size of the Array ");
scanf("%d",&arr_size);
//Get input
printf("Enter %d elements in the array: ",arr_size);
for(i=0; i<arr_size; i++){
printf("Enter %d element",i);
scanf("%d",&arr[i]);
}
//Prints all elements
printf("\n Entered Elements in the array are : ");
for (i=0;i<arr_size;i++)
{
printf("%d, ", arr[i]);
}
//Get the element which needs to be searched
printf("\n Enter the value to be searched ");
scanf("%d",&key);
//Now search using binary search
//Remember binary search can be performed on sorted arrays only
//so if the array is unsorted, we need to use a sorting technique
//like merge sort to sort it first and then apply binary search
lowerbound = 0;
upperbound = arr_size-1;
while(lowerbound <= upperbound ){
midPoint = (lowerbound + upperbound)/2;
if(arr[midPoint] < key ){
//if key is smaller than midpoint
//key will be in upperhalf
lowerbound = midPoint + 1;
}
else if(arr[midPoint] == key) {
//key found at midpoint
result = midPoint+1;
printf("%d found at location %d . \n ",key,result);
break;
}
else{
//if key is larger than midpoint
//key will be in lower half
upperbound = midPoint - 1;
}
}
if(lowerbound > upperbound){
printf("Key Not Found , Please Enter Valid Key !");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment