public class mergesort {
//property
private int [] data;
//konstruktor
public mergesort (int n){
this.data=new int[n];
}
//fungsi set data
public void SetData(int index, int value){
if (index >= 0 && index < this.data.length){
this.data[index]=value;
}
}
//fungsi print data
public void PrintData(){
String out="Data = ";
for(int a=0; a<this.data.length; a++){
out +=this.data[a]+"_";
}
System.out.println(out);
}
//fungsi merge sort
public void Sort(){
//tentukan posisi awal dan akhir
int i=0;
int j = this.data.length-1;
//urutkan
Mersort(i, j);
}
private void Mersort(int start, int end){
//temtukan jumlah data
int n=(end-start+1);
if (n>1){
//hitung nilai tengah
int mid = (start+end)/2;
//rekursif mergesort
Mersort(start, mid);
Mersort(mid+1, end);
//merge
int[]temp=new int[n];
int x=start;
int y=mid+1;
for(int a=0; a<n; a++){
if(x<=mid && y<=end){
if(this.data[x]<this.data[y]){
temp[a]=this.data[x];
x++;
} else {
temp[a]=this.data[y];
y++;
}
} else if (x <= mid){
temp[a]=this.data[x];
x++;
} else {
temp[a]=this.data[y];
y++;
}
}
//salin hasil pengurutan
for(int a=0; a<n; a++){
this.data[start+a]=temp[a];
}
}
}
public static void main(String[]args){
//buat objek
mergesort ms=new mergesort(10);
//input isi
ms.SetData(0, 5);
ms.SetData(1, 3);
ms.SetData(2, 7);
ms.SetData(3, 6);
ms.SetData(4, 9);
ms.SetData(5, 4);
ms.SetData(6, 8);
ms.SetData(7, 2);
ms.SetData(8, 1);
ms.SetData(9, 4);
//print
System.out.println("merge sort");
System.out.println("----------");
ms.PrintData();
//sort
ms.Sort();
//print
ms.PrintData();
}
}
Selasa, 24 Juni 2014
Langganan:
Posting Komentar (Atom)
0 komentar:
Posting Komentar