Binary Search
Binary Search
The Drawback of the Linear search was that, it was not efficient enough when the data set was huge. This Drawback is eliminated when Binary Search algorithm is used. But the drawback of this algorithm is that the data set has to be sorted. In this Algorithm the data set would be divided into 2 equal parts in every iteration till the required element is found or till the case when further equal division is not possible. This algorithm is similar to searching for a particular page in a book. Say for example a book is having 20 pages and 8th page is to be found. Now equal halves of 20 page book is 0-10 pages block and 11-20 pages block. So 8th page falls under 0-10 page block. This continues for few more iterations, till 8th page is reached.
This method needs [log2n]+1 comparisons, i.e O(log n) in Big O notation, i.e. for Thousands of records, it needs about five to six comparisons, which is way better than Linear search.
Below Image shows the formation of the algorithm in binary tree structure.
|| Code Snippet
/* * BinarySearch.c * * Created on: Dec 2, 2016 * Author: karth */ #include <stdio.h> /*Binary search function to search for a key in the List*/ int bin_search(int array[],int size,int key) { int first = 0, last = size - 1, middle = (first+last)/2; while (first <= last) //looping over the array to find the matching element till all elements in each half are compared { if (array[middle] < key) //if element is lesser than the key value first = middle + 1; else if (array[middle] == key) { // if matched with key return middle+1; break; } else { last = middle - 1; // reducing the size of the halves } middle = (first + last)/2; //re-calculating the middle value after each iteration } return 0; } int main() { int n, key, pos; printf("Enter number of elements\n"); scanf("%d",&n); // defining the array size int array[n]; printf("Enter %d integers\n", n); for (int i = 0; i < n; i++) { scanf("%d",&array[i]); // Setting the array elements } printf("Enter value to find\n"); scanf("%d", &key); // Keying in the value which has to be searched pos= bin_search(array,n,key); // Calling the Binary search function if(pos==0) { printf("Search unsuccessful, %d not found.\n", key); // If position of the searching stays at 0 element or beginning } else { printf("%d found at location %d.\n", key, pos); //Printing the value fetched } return 0; }