Tuesday 22 January 2013

binary search


The binary search works with already sorted array elements. Let us say x is to be search on sorted array then first we will compare x element with middle of the array if it success eds then say element found else check if the element is greater or lesser than the x element and follow the same process repeatedly until desired result is found or say not found.

 Here is a C program for binary search :
 #include<stdio.h>  
 #include<conio.h>  
 int count=0;  
 int bin(int item,int a[],int low,int hi)  
 {  
   int mid;  
   if(low>hi)  
   return -1;  
   mid=(low+hi)/2;  
      return (item = = a[mid] ? mid: item<a[mid] ? bin(item,a,low,mid-1):  
    bin(item,a,mid+1,hi));  
 }  
 int main()  
 {  
   int n,i,a[20],item,pos;  
   printf("enter the size of the array \n");  
   scanf("%d",&n);  
   printf("enter the array element \n");  
   for(i=0;i<n;i++)  
   scanf("%d",&a[i]);  
   printf("enter the element to be searched \n");  
   scanf("%d",&item);  
   pos=bin(item,a,0,n-1);  
   if(pos==-1)  
   {  
         printf("element is not found \n");  
   }  
   else  
   {  
     printf("element is present \n");  
   }  
   printf("the number of execution is %d\n",count);  
   getch();  
 }  

รจ 0(nlogn)


1 comment:
Write comments

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2022