package bubble_sort;
import java.util.Random;
public class Main {
public Main(){
}
private int [] data;//membuat data array
//membuat generator untuk mengisi array secara acak
private static Random generator = new Random();
public Main(int size){
data = new int [size];//ukuran array
for(int i = 0; i < size; i++)
data[i]=10 + generator.nextInt(90); }
//Tahap sorting / pengurutan
public void sort()
{for(int i=0; i<data.length-1; i++)
{for(int index=0; index<data.length-1-i; index++){
if(data[index] > data[index+1]) //pengecekan nilai data
{ change (index, index+1);//penukaran position di bubble sort
printPass(index, index+1, data.length);//menampilkan data setelah penukaran posisi
}}
}}
public void change(int first, int second)
{int temporary = data[first];
data[first] = data[second];
data[second] = temporary; }
public void printPass(int pass, int index, int length)
{ for (int i=0; i<pass; i++)//loop data array
System.out.print(data[i]+" ");//menampilkan array
if (pass==index-1)
{ System.out.print(data[pass]+"* ");//menandai array yg dipindahkan
System.out.print(data[index]+"* "); }//menandai array yg dipindahkan
for ( int j = index+1;j<data.length; j++ )//looping data yg belum di sorting
{System.out.print( data[ j ] + " " );}//menampilkan array yang belum disorting
System.out.println("\n");}// Membuat baris baru
public String toString()
{
StringBuffer temporary=new StringBuffer();
for (int element:data)
temporary.append(element + " ");
temporary.append("\n");
return temporary.toString();
}
public static void main(String[] args) {
Main sortArray=new Main(7);//menginisialisasikan jumlah data dalam array
System.out.println("DATA ARRAY SEBELUM DISORTING:");
System.out.println(sortArray);//menampilkan data sebelum sorting
sortArray.sort();//menampilkan tahap pengurutan(sorting)
System.out.println("DATA ARRAY SETELAH DISORTING:");
System.out.println(sortArray);//menampilkan hasil sorting
}
}
Tidak ada komentar:
Posting Komentar