public class QuickSort {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int i;
int array[] = {12, 9, 4, 99, 120, 1, 3, 10};
System.out.println("value before the sort:\n");
for (i = 0; i < array.length; i++){
System.out.print(array [i] + " ");
}
System.out.println();
quicksort(array, 0, array.length-1);
System.out.println("values after the sort:\n");
for (i =0; i < array.length; i++){
System.out.print(array [i] + " ");
}
System.out.println();
System.out.println("pause");
}
public static int partition (int arr[], int left, int right){
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j){
while (arr[i] < pivot){
i++;
}
while (arr[j] > pivot){
j--;
}
if (i <= j){
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
return i;
}
public static void quicksort (int arr[], int left, int right){
int index = partition(arr, left, right);
if (left < index - 1){
quicksort(arr, left, index - 1);
}
if (index < right){
quicksort(arr, index, right);
}
}
}
Tidak ada komentar:
Posting Komentar