Binary search code in c with algorithm

 BINARY SEARCH:

This method is called binary search, as we have divided the list to be searched every time

into two lists and the search is done in only one of the lists. Consider that the list is sorted in

ascending order. In binary search algorithm, to search for a particular element, it is first

compared with the element at the middle position, and if it is found, the search is successful,

else if the middle position value is greater than the target, the search will continue in the first

half of the list; otherwise, the target will be searched in the second half of the list. The same

process is repeated for one of the halves of the list till the list is reduced to size one.

Algorithm depicts the logic behind this type of search.

algorithm 

1. Let n be size of the list

Let target be the element to be searched

Let flag = 0, low = 0, high = n-1

2. if low £ high, then

middle = (low + high)/2


else go to step (5)

3. if(key[middle] = target)

Position = middle, fl ag = 1

Go to step (5)

else if(key[middle] > target) then

high = middle − 1

else

low = middle + 1

4. Go to step(2)

5. if flag = 1

report as target element found at location ‘position’

else

report that element is not found in the list

6. stop


CODE (C LANGUAGE)

/* BINARY SEARCH


#include<stdio.h>
int main()
{  
    int n,i,j,key;
    printf("enter the value of n: \n");
    scanf("%d",&n);
    int a[n];
    printf("\nenter the elements of array:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("sorted array is:");
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
     i=0;
    j=n-1;
    int flag=0;
    printf("\nenter element to be searched:");
    scanf("%d",&key);
    while(i<=j)
    {
        int m=(i+j)/2;
        if(a[m]==key)
        {
            flag=1;
            break;
        }
        else if(key>a[m])
        i=m+1;
        else
        j=m-1;
    }
    if(flag==1)
    printf("\nElement found");
    else
    printf("\nnot found");
}
*/



Post a Comment

Previous Post Next Post