Created
November 21, 2017 00:59
-
-
Save sugiartocokrowibowo/86528f1e27e545f5d3a4a54b372f09a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Sorting { | |
public static void main(String[] args) { | |
Sorting sort = new Sorting(); | |
int[]data = {12,2,9,1,8,2,3}; | |
System.out.print("Data : "); | |
sort.cetakArray(data); | |
System.out.print("Sorting Alg. BubbleSort : "); | |
sort.cetakArray(sort.bubble(data)); | |
System.out.print("Sorting Alg. SelectionSort: "); | |
sort.cetakArray(sort.selection(data)); | |
System.out.print("Sorting Alg. QuickSort : "); | |
sort.cetakArray(sort.quick(data)); | |
} | |
private void cetakArray(int[]input){ | |
System.out.print("["); | |
for(int i=0;i<input.length;i++){ | |
System.out.print(" "+input[i]+" "); | |
} | |
System.out.println("]"); | |
}//end of cetakArray( ) | |
private void tukar(int[]input, int i, int j){ | |
int[]data = input; | |
if(i>=0&&j>=0&&i<data.length&&j<data.length){ | |
int temp= data[i]; | |
data[i] = data[j]; | |
data[j] = temp; | |
} | |
} | |
private int[] selection(int[]input){ | |
int[]data = (int[]) input.clone(); | |
int n = data.length; | |
for(int i=0;i<n-1;i++){ | |
for(int j=1+i;j<n;j++){ | |
if(data[i]>data[j]){ | |
//tukar | |
tukar(data,i,j); | |
} | |
} | |
} | |
return data; | |
}//end of selectionSort(int[]input) | |
private int[] bubble(int[]input){ | |
int[]data = (int[]) input.clone(); | |
int n = data.length; | |
for(int j=n-2;j>0;j--){ | |
for(int i=0;i<=j;i++){ | |
if(data[i]>data[i+1]){ | |
//tukar | |
tukar(data,i,i+1); | |
} | |
} | |
} | |
return data; | |
}//end of bubbleSort(int[]input) | |
private int[] quick(int[]input){ | |
int[]data = (int[]) input.clone(); | |
int n = data.length; | |
partisi(data,0,n-1); | |
return data; | |
}//end of quickSort(int[]input) | |
private void partisi(int[]input, int low, int high){ | |
int i = low; | |
int j = high; | |
int pivot = input[low + (high-low)/2]; | |
//cari pasangan bilangan untuk ditukar | |
while(i<=j){ | |
while(input[i]<pivot){i++;} | |
while(input[j]>pivot){j--;} | |
if(i<=j){ | |
//TUKAR | |
tukar(input,i,j); | |
i++; | |
j--; | |
} | |
}//end of while(i<=j){ | |
if (low<j){partisi(input, low, j);}//Memanggil fungsi partisi() secara rekursif untuk interval (low, j) | |
if (i<high){partisi(input, i, high);}//Memanggil fungsi partisi() secara rekursif untuk interval (i, high) | |
}//end of partisi( ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment