Pages

Subscribe:

Binary Search Using C Program

A sorted array is searched by Binary search.If the array is sorted , we can employ binary search , which brilliantly halves the size of the search space each time it examines one array element.Binary  means two , so it divides an array two halves for searching . This searching is applicable only to an ordered table ( in either ascending or in descending order ) .



Program code :


#include<stdio.h>
#include<conio.h>
void binary_search(int [],int,int); 
void main()
{
char ch;
int arr[100],v,size,i;
do{
    clrscr();
    printf("\t Enter array size : ");
    scanf("%d",&size);

    for(i=0;i<size;i++)
    {
        printf("\n\t Enter element :");
        scanf("%d",&arr[i]);
        
    }
    printf("\n\t Search element :");
    scanf("%d",&v);
    binary_search(arr,v,size);
    printf("\n\t Continue (y/n):");
    ch=getch();
    
  }while(ch=='y'||ch=='Y');
}

void binary_search(int arr[],int v,int size)
{
int found=0;
int high=size-1,low=0,mid;
mid=(high+low)/2;
printf("\n\t Looking for %d\n\t",v);
while((!found)&&(high>=low))
    {
    printf("Low:%d  Mid:%d  High:%d\n\t",low,mid,high);
    if(v==arr[mid])
        {
        printf("Key value found at position %d",mid+1);
        found=1;
        }
    else
        {
            if(v<arr[mid])
                high=mid-1;
            else
                low=mid+1;
        mid=(high+low)/2;
        }
    }
    
    if(found==1)
    printf("\n\t Search sucessful");
    else
    printf("\n\t key value not found");
}


Output :

Binary search



If you have any Further Information and Quires about this Article don't hesitate to comment in comment box below.
                                                           AND

 If you like this article , like our Facebook like page and click  +1 to support 123techguide
comments powered by Disqus
 

Listed In

Bloggers - Meet Millions of Bloggers http://Link-exchange.comxa.com
Blog Search: The Source for Blogs Internet Blogs

Disclaimer

The contents in this blog are taken from various sources available over the internet, therefore we do not gurantee of it's accuracy, if you find any of the content in the blog is infringing it's copyright, please do email us on '123techguide@gmail.com' and we will make sure to remove the same from the blog at the earliest.