9. Ada beberapa kumpulan data sebagai berikut :
2 8 3 5 6 4 11 1 9
Urutkan kumpulan data di atas menggunakan quick sort serta gambarkan step by step dari
sorting tersebut !
Source Code :
# include <iostream>
# include <iomanip>
# include <conio.h>
using namespace std;
void q_sort(int[],int,int);
int main ()
{
int NumList[9]={2,8,3,5,6,4,11,1,9};
cout<<" Data Sebelum diurutkan: \n";
for(int d=0;d<9;d++)
{
cout<<setw(3)<<NumList[d];
}
cout<<"\n\n";
q_sort(NumList,0,9);
cout<<" Data setelah diurutkan: \n";
for(int iii=0;iii<9;iii++)
cout<<setw(3)<<NumList[iii]<<endl<<endl;
getch();
}
void q_sort(int numbers[],int left,int right)
{
int pivot,l_hold,r_hold;
l_hold=left;
r_hold=right;
pivot=numbers[left];
while(left<right)
{
while((numbers[right]>=pivot)&&(left<right))
right--;
if(left!= right)
{
numbers[left]=numbers[right];
left++;
}
while((numbers[left]<=pivot)&&(left<right))
{
left++;
}
if (left!=right)
{
numbers[right]=numbers[left];
right--;
}
}
numbers[left]=pivot;
pivot=left;
left=l_hold;
right=r_hold;
if(left<pivot)
q_sort(numbers,left,pivot-1);
if(right>pivot)
q_sort(numbers,pivot+1,right);
}
Output :
2 8 3 5 6 4 11 1 9
Urutkan kumpulan data di atas menggunakan quick sort serta gambarkan step by step dari
sorting tersebut !
Source Code :
# include <iostream>
# include <iomanip>
# include <conio.h>
using namespace std;
void q_sort(int[],int,int);
int main ()
{
int NumList[9]={2,8,3,5,6,4,11,1,9};
cout<<" Data Sebelum diurutkan: \n";
for(int d=0;d<9;d++)
{
cout<<setw(3)<<NumList[d];
}
cout<<"\n\n";
q_sort(NumList,0,9);
cout<<" Data setelah diurutkan: \n";
for(int iii=0;iii<9;iii++)
cout<<setw(3)<<NumList[iii]<<endl<<endl;
getch();
}
void q_sort(int numbers[],int left,int right)
{
int pivot,l_hold,r_hold;
l_hold=left;
r_hold=right;
pivot=numbers[left];
while(left<right)
{
while((numbers[right]>=pivot)&&(left<right))
right--;
if(left!= right)
{
numbers[left]=numbers[right];
left++;
}
while((numbers[left]<=pivot)&&(left<right))
{
left++;
}
if (left!=right)
{
numbers[right]=numbers[left];
right--;
}
}
numbers[left]=pivot;
pivot=left;
left=l_hold;
right=r_hold;
if(left<pivot)
q_sort(numbers,left,pivot-1);
if(right>pivot)
q_sort(numbers,pivot+1,right);
}
Output :
Comments
Post a Comment