Searching Algorithm: Binary Search
Searching Algorithm: Binary Search
Binary Search
Binary search
In this search technique we divide the given array into
two halves at each level and look for the key element in
one of the two halves.
This algorithm works only for sorted array.
It is similar to searching a word in a dictionary. We
roughly start from the middle, and if we are looking for
a word starting with say E then we discard the other
half and repeat the process till we get the result.
Example
Consider an array arr having 10 elements
1 2 3 4 5 6 7 8 9 10
Is 2 present in arr ?
NO
New Range
YES
#include<stdio.h>
//function declaration
int binarySearch(int *a, int n, int key);
int main(){
//variable declaration
int arr[10], i, key;
//input
printf("Enter elements of the array: ");
for(i=0; i<10; i++){
scanf("%d",&arr[i]);
printf("Enter key: ");
scanf("%d", &key);
//search
i=binarySearch(arr, 10, key);
//output
if(i == -1)
printf("Key not found: ");
else
printf("Key at index: %d\n", i);
return 0;
}
//function declaration
int binarySearch(int *a, int n, int key){
int start = 0, end = n-1, mid = (start+end)/2;
while(start<=end && a[mid]!=key){
if(key<a[mid])
end=mid-1;
else
start=mid+1;
mid=(start+end)/2;
}
if(start>end)
return -1; //key not found
return mid;
}
}