F How to implement Binary Search program and sort the given values using pointer? | CodeTheta

How to implement Binary Search program and sort the given values using pointer?

January 17, 2014


/* http://native-code.blogspot.com */

#include<stdio.h>
#include<conio.h>
void input(int*,int);
void sort(int*,int) ;
int binary_search(int*,int,int) ;
void display(int*,int);
void main()
{
int a[20],i,item,n,p;
clrscr();
printf("\n enter the no of range");
scanf("%d",&n) ;
input(a,n);
printf("\n before sorting:");
display(a,n);
sort(a,n) ;
printf("\n after sorting: ");
display(a,n) ;
printf("\n enter the item you want to search");
scanf("%d",&item);
p=binary_search(a,n,item);
if(p==0)
printf("searched item is not found");

else
printf("\n searched item is found at %d",p);
getch();
}
 /* http://native-code.blogspot.com */
void input(int a[],int lim)
{
int i;
printf("\n enter the no: ");
for(i=0;i<lim;i++)
  scanf("%d",&a[i]);
}

 /* http://native-code.blogspot.com */
void sort(int *a,int lim)
{
int  i,j,t;

for(i=0;i<lim-1;i++)
{
  for(j=i+1;j<lim;j++)
  {
    if(*(a+i)>*(a+j))
    {  t=*(a+i) ;
       *(a+i)=*(a+j);
       *(a+j)=t;
    }
  }
}
}

/* http://native-code.blogspot.com */
void display(int a[],int lim)
{
int  i;
for(i=0;i<lim;i++)
   printf("%d ",a[i]) ;
}

int binary_search(int *a,int lim,int item)
{
 int beg,end,mid;
 beg=0;
 end=lim;
 mid=(beg+end)/2;
 while(*(a+mid)!=item && beg<end)
 {
 if(item>*(a+mid))
 beg=mid+1;
 else
 end=mid-1;
  mid=(beg+end)/2;
 }
 return(mid+1);
 }

 /* http://native-code.blogspot.com */

Post a Comment