Monday, 25 February 2019

Iterative Binary Search in C without using function

Binary search algorithm is one of the most efficient searching algorithm. The precondition of binary search algorithm is that the set of elements e.g array must be ordered (sorted) in particular order.

Binary search begins by finding the middle element of the set and comparing it with the key value. If key value is smaller than middle element, it means all elements from middle element to last element of the set are greater than key value, so they must not be searched and should be discarded. So now the new set should comprise of elements from first to element just before middle element. If key value is greater than middle element, it means all elements from first element to middle element of the set are smaller than key value, so they must not be searched and should be discarded. So now new set should comprise of elements from first element after middle element to last element. If key value is equal to middle element, then index of middle element is returned.

//Iterative binary search in C without using function
#include <stdio.h>
int main()
{
    int array[] = {9,10,12,15,32,50};
    int key = 17,arraySize=0,i,index=-1,first,last,mid;

    //finding the size(no of elements) of array
    arraySize = sizeof(array)/ sizeof(int);

    first=0;
    last=arraySize-1;
    while(first<=last)
    {
        mid=(first+last)/2; //index of middle element
        if(key<array[mid])
        {
            last=mid-1;
        }
        else if(key>array[mid])
            first=mid+1;
        else{
            index=mid;
            break;
        }
           
    }

    if(index!=-1)
        printf("Element %d found at position %d.\n",key,index+1);
    else
        printf("Element %d not exist in given set of elements.\n",key);

    return 0;
}
Output: key=15;
Output: key=10;
Output: key=17;

Please comment if you find anything incorrect, or you want to improve the topic discussed above. 

No comments:

Post a Comment