The BOTTOM LINE Quote Of The Day

The BOTTOM LINE Quote Of The Day

Don't Ever Tell GOD How BIG Your Problems are.
Just Tell Your Problems How BIG your GOD is ;)

Wednesday, January 5, 2011

Linear And Binary Search

#include<stdio.h>
#include<conio.h>
#define max 20


 int data[max];


 void input_data();
 void disp_data(int [],int);
 void Sort(int [],int);
 void Lsearch(int [],int,int);
 void Bsearch(int [],int,int);


void main()
 {
  clrscr();
  int i,num,cho,sbch,item,ssbch;
  do
  {
  printf("Enter the no. of students :- ");
  scanf("%d",&num);
  }while( num <= 0 ||  num >= max );
  printf("\n\n Enter the data of the %d elements : ",num);
  for(i=0;i<num;i++)
   scanf("%d",&data[i]);
  disp_data(data,num);
  getch();
  do
  {
  clrscr();
  printf("\n\n\t\t\t  Menu Selection\n");
  printf("\n 1. Linear Seaching of an Element in an Array ");
  printf("\n 2. Binay Sorting of an Element in an Array ");
  printf("\n Enter your choice :- ");
  scanf("%d",&cho);
  if(cho==1 || cho==2)
  {
   printf("\n\nEnter any number to be searched : ");
   scanf("%d",&item);
  }
  switch(cho)
   {
    case 1: Lsearch(data,num,item);
   break;
    case 2: Bsearch(data,num,item);
   break;
    default: break;
   }
  if( cho == 1 || cho == 2 )
   disp_data(data,num);
  }while( cho == 1 || cho == 2 );
  getch();
 }


void disp_data(int s[],int noe)
 {
  int i;
  printf("\n\n\t\t The current data is :");
  for(i=0;i<noe;i++)
   printf(" %d",s[i]);
  getch();
 }


 void Sort(int x[],int noe)
  {
   int i,j,flag,small,posn,temp;


   for(i=0;i<noe;i++)
   {
    flag = 0;
    small = x[i];
    for(j=i+1;j<noe;j++)
    {
     if( x[j] < small )
      { small = x[j];  flag = 1; posn = j; }
    }
    if(flag==1)
     {
     temp = x[i];
     x[i] = x[posn];
     x[posn] = temp;
     }
   }
   printf("\n\n\t\t Sorting has been done ... \n\n");
  }


 void Lsearch(int x[],int noe,int ele)
  {
    int flag=0,i,noc=0,posn;
    for(i=0;i<noe;i++)
     {
      noc++;
      if(ele == x[i])
       {  flag = 1;  posn = i;  break;  }
     }
    if(flag==0)
     printf("\n\nThe data not found ");
    else
     {
      printf("\n\nThe data has been found at position #%d",posn+1);
      printf("\n& The no. of comparisions were made : %d",noc);
      }
    getch();
  }


void Bsearch(int x[],int noe,int ele)
   {
     int flag=0,i,noc=0,posn,beg,last,mid;
     beg = 0; last = noe - 1;
     Sort(x,noe);
     while(beg<=last)
      {
       mid = (beg+last)/2;
       noc++;
       if(ele == x[mid])
{
flag = 1;
posn = mid;
break;
}
       else if(ele > x[mid])
beg = mid + 1;
       else
last = mid - 1;
      }
     if(flag==0)
      printf("\n\nThe data not found ");
     else
      {
      printf("\n\nThe data has been found at position #%d",posn+1);
      printf("\n& The no. of comparisions were made : %d",noc);
      }
      getch();
   }

No comments:

Post a Comment