#include <conio.h>
using namespace std;
int total,data[10],salin[10];
void input()
{
cout<<"merge sort\n\n";
cout<<"Masukkan berapa banyak arraynya = ";
cin>>total;
cout<<"\n";
for(int a=0;a<total;a++)
{
cout<<"\nMasukkan nilai pada INDEX ke ["<<a+1<<"] = ";
cin>>data[a];
}
}
void merge(int salin[],int lowptr,int highptr,int upperbound)
{
int x=0;
int lowerbound=lowptr;
int mid=highptr-1;
int n=upperbound-lowerbound+1;
while(lowptr<=mid && highptr<=upperbound)
{
if(data[lowptr]<data[highptr])
{
salin[x++]=data[lowptr++];
}
else
{
salin[x++]=data[highptr++];
}
while(lowptr<=mid)
{
salin[x++]=data[lowptr++];
}
while(highptr<=upperbound)
{
salin[x++]=data[highptr++];
}
for(int a=0;a<n;a++)
{
data[lowerbound+a]=salin[a];
}
}
}
void devide(int salin[],int kiri,int kanan)
{
if(kiri<kanan)
{
int mid=(kiri+kanan)/2;
devide(salin,kiri,mid);
devide(salin,mid+1,kanan);
merge(salin,kiri,mid+1,kanan);
}
}
void sort()
{
devide(salin,0,total);
}
void view()
{
for(int a=0;a<total-1;a++)
{
cout<<data[a]<<" ";
}
cout<<"\n";
getch();
}
int main()
{
input();
cout<<"sebelum di- sorting :";
view();
sort();
cout<<"sesudah di- sorting :";
view();
}
0 Comments