快速排序
程序员文章站
2022-03-24 12:41:12
...
/*
* 快速排序非优化算法,参考《算法导论》第二版85页
*/
public class QuickSort {
public static int a[]={5,22,12,98,32,75,22,73,9,88,2222,321,923,56,23,78,56};
public static void main(String[] args) {
quickSort(a,0,a.length-1);
p(0,a.length-1);
}
private static void p(int low,int high) {
for(int i=0;i<a.length;i++){
System.out.print(a[i]+",");
}
}
private static void quickSort(int[] array, int low, int high) {
if (low < high) {
int p = partition(array, low, high);
quickSort(array, low, p - 1);
quickSort(array, p + 1, high);
}
}
private static int partition(int[] array, int low, int high) {
int s = array[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (array[j] < s) {
i++;
swap(array, i, j);
}
}
swap(array, ++i, high);
return i;
}
private static void swap(int[] array, int i, int j) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}