Thursday, June 7, 2012

Binary Search C++ Implementation

/*binary search ascending*/
#include<stdio.h>
#include<conio.h>
main()
{
       int i,j,indexmin,tengah,eltengah,n,dt,temp,ketemu=0,posisi;
       int data[100];
       ulang:
       printf("banyak data: ");
       scanf("%i",&n);
       for(i=0;i<n;i++)
       {
                       printf("Masukkan data ke-%i = ",i+1);
                       scanf("%i",&data[i]);
       }
       for(i=1;i<n;i++)
       {
                       temp=data[i];
                       j=i-1;
                       while((data[j]>=temp)&&(j>0))
                       {
                                                    data[j+1]=data[j];
                                                    j=j-1;
                       }
                       if(temp>=data[j]) data[j+1]=temp;
                       else
                       {
                           data[j+1]=data[j];
                           data[j]=temp;
                       }
                       }
      
       printf("setelah pengurutan\n");
       for(i=0;i<n;i++)
       printf("%d  ",data[i]);
       printf("\n Data yang dicari : ");scanf("%i",&dt);
       ketemu==0;
       tengah=(n/2)+1;
       eltengah=data[tengah];
       i=0;
       if(dt==eltengah)
       {
                       ketemu=1;
                       posisi=tengah;
       }
       else
       {
           if(dt<eltengah)
           {
                          i=0;
                          while((ketemu==0)&&(i<tengah)&&(data[i]<=dt))
                          {
                                                           if(data[i]==dt)
                                                           {
                                                                          ketemu=1;
                                                                          posisi=1;
                                                           }
                                                           else
                                                           i=i+1;
                          }
           }
           else
           {
               i=tengah+1;
               while((ketemu==0)&&(i<n)&&(data[i]<=dt))
               {
                                                if(data[i]==dt)
                                                {
                                                               ketemu=1;
                                                               posisi=1;
                                                }
                                                else
                                                i=i+1;
               }
           }
       }
       if(ketemu==0)
       printf("%d data tidak ditemukan\n",dt);
       else
       printf("%d ditemukan pada posisi %d\n",dt,posisi+1);
       goto ulang;
       getch();
}

No comments:

Post a Comment