//property
private int [] data;
//konstruktor
public insertionsort (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 tukar nilai
private void Tukar(int i, int j){
int temp = this.data[i];
this.data[i]=this.data[j];
this.data[j]=temp;
}
//fungsi insertion sort
public void Sort(){
for(int a=1; a<this.data.length-1; a++){
int b=a;
while(b>0 && this.data[b]< this.data[b-1]){
Tukar(b, b-1);
b--;
}
}
}
public static void main(String[]args){
//buat objek
insertionsort is=new insertionsort(10);
//input isi
is.SetData(0, 5);
is.SetData(1, 3);
is.SetData(2, 7);
is.SetData(3, 6);
is.SetData(4, 9);
is.SetData(5, 4);
is.SetData(6, 8);
is.SetData(7, 2);
is.SetData(8, 1);
is.SetData(9, 4);
System.out.println("insertion sort");
System.out.println("--------------");
is.PrintData();
//sort
is.Sort();
is.PrintData();
}
}
0 komentar:
Posting Komentar