Thursday, June 13, 2013

C/C++ programing to search an element from array using binary search.


#include<stdio.h>

#include<conio.h>

int main()

{

      int n,DATA[13]={ 11 , 22 , 30 , 33 ,40 , 44 , 55 , 60 , 66 , 77 , 80 , 88 , 99  };

      int LB=0,UB=12,ITEM,LOC;

      int BEG,END,MID;

      BEG=LB;

      END=UB;

      MID=(BEG+END)/2;

      printf(“The Given Array is: \n”);

      for(n=0;n<12;n++)

      {

            printf(“%d\n”,DATA[n]);

      }

      printf(“Enter The Item to be Searched: “);

      scanf(“%d”,&ITEM);

      while((BEG<=END)&&(DATA[MID]!=ITEM))

      {

          if(ITEM<DATA[MID])

          {

                 END=MID-1;

          }

          else

          {

                 BEG=MID+1;

          }

          MID=(BEG+END)/2;

      }

      if(DATA[MID]==ITEM)

     {

          printf(“LOC= %d”,MID);

     }

     else

     {

           printf(“LOC=%d”,-1);

    }

    getch();

    return 0;

} 

No comments:

Post a Comment