selection sort is a sorting by using a comparator. comparison this time using a comparison of maximum and minimum simultaneously from right and left. The following source code more:
Running results :
#include <cstdlib> #include <iostream> using namespace std; class Sorting { public : Sorting (){ cout<<"Program sorting"<<endl<<endl; } void input(); void selection_sort(); void cetak(); void tukar(int&a, int&b); void maksmin(int, int, int&, int&); private : int i, j, n; int x[100]; }; void Sorting::input(){ cout<<"Banyak data : "; cin>>n; for(i = 0; i < n; i++){ //perulangan for cout<<"Data ke-"<<(i + 1)<<" : "; cin>>x[i]; //input array 1 dimension } } void Sorting::cetak(){ for(i = 0; i < n; i++){ //loop for cout<<x[i]<<" "; } cout<<endl; } void Sorting::tukar(int&a, int&b){ int temp; temp=a; a=b; b=temp; } void Sorting::selection_sort(){ int posmin, posmaks; int i = 0; int j = n-1; while(i <= j){ //loop while maksmin(i,j, posmin,posmaks); tukar(x[i], x[posmin]); maksmin(i,j, posmin,posmaks); tukar(x[j], x[posmaks]); i++; j--; } } void Sorting :: maksmin(int awal, int akhir, int & posmin, int & posmaks){ int maks=x[akhir]; int min=x[awal]; posmin = awal; posmaks = akhir; for(i = awal; i<= akhir; i++){ if(x[i] > maks){ maks=x[i]; posmaks = i; } if(x[i]< min){ min = x[i]; posmin = i; } } } int main() { Sorting a; a.input(); cout<<"\nData sebelum disorting :"<<endl; a.cetak(); a.selection_sort(); cout<<"\nSorting menggunakan selection sort : "<<endl; a.cetak(); cout<<"\n\n"; system("PAUSE"); system("cls"); return main (); }
Running results :