Searching Algorithm
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 ?
Binary Search woks only for sorted elements
Searching for 2
Index 0 1 2 3 4 5 6 7 8 9
Given array
Value 1 2 3 4 5 6 7 8 9 10
Start index: 0 End index: 9
𝑠𝑡𝑎𝑟𝑡+𝑒𝑛𝑑 0+9
Mid index = = = 4 (taking the integer part only)
2 2
Searching for 2
Index 0 1 2 3 4 5 6 7 8 9
Given array
Value 1 2 3 4 5 6 7 8 9 10
NO
New Range
is arr[mid] i.e., arr[4]=2 ?
Start index: 0 End index: 9
𝑠𝑡𝑎𝑟𝑡+𝑒𝑛𝑑 0+9
Mid index = = = 4 (taking the integer part only)
2 2
As 2<arr[mid] i.e., 5 so we will search the left half.
Searching for 2
New array range Index 0 1 2 3
VALUE 1 2 3 4
YES
is arr[mid] i.e., arr[1]=2 ?
Start index: 0 End index: 3
𝑠𝑡𝑎𝑟𝑡+𝑒𝑛𝑑 0+3
Mid index = = = 1 (taking the integer part only)
2 2
Search successful!
Key at index: 1
About Binary Search
• It works only for sorted array.
• At each level the array is halved and the key is
searched in any one of the half while the other half is
rejected.
• Best case occurs when the key we are looking for is
present in the middle of the array.
• Worst case occurs when the key is not present.
Algorithm
/*a[0:n-1] is an array of n elements, key is the element being searched.
*/
BinarySearch(a,n,key)
Begin
Set start = 0, end = n-1, mid = (start + end)/2;
while(start<=end && a[mid]!=key) do
if(key< a[mid]) then
Set end= mid-1;
else
Set start = mid + 1;
endif
Set mid=(start + end)/2;
endwhile
if(start>end)
return -1; // key not found
return mid; // returning key index
End
Order of binary search
If there are n elements in the array
Then in each level the array is halved and the search is
reduced to one half of the array.
For n elements there will be log 2 𝑛 iteration.
So, order of Binary Search is O(log 2 𝑛).
Write a program in C to enter 10
elements and search for a key
element using Binary search
/* binary search example
*/
#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;
}
}