Minggu, 07 Juni 2015

Code C : Sequantial and Binary (SEARCHING)

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

#define max 100
int p,q;
int data[max];
int sequensialsearch(int x){
int i=0;
bool ketemu=false;
while((!ketemu)&&(i<max)){
if(data[i]==x)
ketemu=true;
else{
i++;p++;
}
}
if(ketemu)
return i+1;
else
return -1;
}
void tukar(int *a, int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}

void quicksort(int l, int r){
int i,j,x;
x=data[(l+r)/2];
i=l;
j=r;
while(i<=j){
while(data[i]<x)
i++;
while(data[j]>x)
j--;
if(i<=j){
tukar(&data[i],&data[j]);
i++;j--;
}
}
if(l<j)
quicksort(l,j);
if(i<r)
quicksort(i,r);
}

int binarysearch(int x){
int l=0,r=max-1,m;
bool ketemu=false;
while((l<=r)&&(!ketemu)){
m=(l+r)/2;
if(data[m]==x)
ketemu=true;
else if(x<data[m])
r=m-1;
else
l=m+1;
q++;
}
if(ketemu)
return m;
else
return -1;
}

int main(){
int i;
printf("\nData :");
for(i=0;i<max;i++){
data[i]=rand()/1000+1;
printf("%d ",data[i]);
}
int kunci;
printf("\nKunci : ");
scanf("%d",&kunci);
quicksort(0,max-1);
int ketemu1=sequensialsearch(kunci);
int ketemu=binarysearch(kunci);
printf("Perbandingan pada sequensial dan binary adalah %d banding %d",p,q);

getch();
return 0;
}

Tidak ada komentar:

Posting Komentar

Me

Foto saya
I'm 18 year old I'm ugly I'm lazy I do what I want I'm poor I want to learn and I want make money