Jumat, 03 Juni 2011

Selection Sort

 Ini merupakan program sorting untuk mencari fungsi maksimum dan minimum :

#include <cstdlib>
#include <iostream>

using namespace std;

      class Sorting {
            public :
                   Sorting (){
                    cout<<"Program sorting"<<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<<"Masukkan sejumlah angka = ";
           cin>>n;
           for(i = 0; i < n; i++){
                 cout<<"masukkan angka ke "<<i + 1<<" = ";
                 cin>>x[i];
                 }
         
           }
      void Sorting::cetak(){
           for(i = 0; i < n; i++){
                 cout<<x[i]<<"\t";
                 }
           cout<<endl;
           cout<<"min : "<<x[0]<<endl;
           cout<<"max : "<<x[n-1]<<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){
                   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 urut;
    urut.input();
    urut.cetak();
    urut.selection_sort();
    cout<<"sorting menggunakan selection sort = "<<endl;
    urut.cetak();
  
    system("PAUSE");
    system("cls");
    return main ();
}

Tidak ada komentar:

Posting Komentar