Quick Sort & Binary Search
Program Quick Sort & Binary Search
#include <iostream>
using namespace std;
/* binary search
quick sort */
struct sepatu
{
int harga;
string merk;
} data[10];
void quick_sort(sepatu arr[], int left, int right)
{
int i = left, j =
right;
string pivot =
arr[(left+right)/2].merk;
sepatu tukar;
while (i<j)
{
while (arr[i].merk
< pivot)
{
i++;
}
while (arr[j].merk
> pivot)
{
j--;
}
if (i<=j)
{
tukar =
arr[i];
arr[i] =
arr[j];
arr[j] =
tukar;
i++;
j--;
}
}
if (left < j)
{
quick_sort(arr,
left, j);
}
else if (i < right)
{
quick_sort(arr, i,
right);
}
}
main()
{
int batas;
int tukar;
string cari;
cout<<"masukkan batas : ";
cin>>batas;
for(int x=1;
x<=batas; x++)
{
cout<<"masukkan merk
: ";
cin>>data[x].merk;
cout<<"masukkan harga
: ";
cin>>data[x].harga;
cout<<"____________________\n";
}
quick_sort(data,1,batas);
cout<<"
DATA TERURUT \n";
cout<<"==============================\n";
for(int x=1;
x<=batas; x++)
{
cout<<"masukkan merk
: "<<data[x].merk<<endl;
cout<<"masukkan harga
: "<<data[x].harga<<endl;
cout<<"==============================\n";
}
cout<<"
masukkan merk yang dicari : ";
cin>>cari;
int bot=1;
int top=batas,mid;
int i;
for(int
x=1;x<=batas;x++)
{
mid = (bot+top)/2;
if( cari==data[mid].merk
)
{
i = 0;
}
else if(cari <
data[mid].merk)
{
top = mid-1;
}
else
{
bot = mid+1;
}
}
if(i==0)
{
cout<<"Data
ditemukan pada indeks ke-"<<mid<<endl;
}
else
{
cout<<"Data
tidak ditemukan"<<endl;
}
}
Comments
Post a Comment