Senin, 19 November 2012

CONTOH PROGRAM BUBBLE SORT DAN SELECTION SORT


1.      Bubble sort
#include<iostream>
using namespace std;
void bubbleSort(int data [], int n)
{
            int i,temp,flag;
            while(flag){
                        flag=0;
                        for(i=0;i<n;i++){
                                    if(data[i]>data[i+1]){
                                                temp=data[i];
                                                data[i]=data[i+1];
                                                data[i+1]=temp;
                                                flag++;
                                    }
                        }
            }
}
int main ()
{
            int data [100];
            int n,i;
            cout<<endl;
            cout<<"BUBBLE SORT"<<endl;
            cout<<endl;
            cout<<"masukkan jumlah data : ";
            cin>>n;
            for(i=0;i<n;i++){
                        cout<<"Data ["<<i<<"] = ";
                        cin>>data[i];
                        cout<<endl;
            }
            bubbleSort(data,n);
            cout<<"Hasil Pengurutan : "<<endl;
            for(i=0;i<n;i++)
                        cout<<"  "<<data[i];
}
2.      Selection sort
#include<iostream>
using namespace std;
void tampilan_larik(int data[],int n)
{
            int i;
            for(i=0;i<n;i++)
                        cout<<data[i]<<" ";
            cout<<endl;
}
void selection_sort(int data[],int n)
{
            int M, A, j, y;
            for(A=0;A<n-1;A++){
                        M=A;
                        for(j=A+1;j<n;j++){
                                    if(data[M]>data[j])
                                                M=j;
                        }
                        y=data[A];
                        data[A]=data[M];
                        data[M]=y;
                        cout<<"Hasil A="<<A<<" : ";
                        tampilan_larik(data,n);
                        cout<<endl;
            }
}
int main ()
{
            int n,i,data[100];
            cout<<endl;
            cout<<"masukkan jumlah data : ";
            cin>>n;
            cout<<endl;
            for(i=0;i<n;i++){
                        cout<<"Data ["<<i<<"] = ";
                        cin>>data[i];
                        cout<<endl;
            }
            selection_sort(data,n);
            cout<<"Hasil pengurutan : "<<endl;
            cout<<endl;
            tampilan_larik(data,n);
            return 0;
}