算法描述:對於一組給定的記錄,通過一趟排序后,將原序列分為兩部分,其中前一部分的所有記錄均比后一部分的所有記錄小,然后再依次對前后兩部分的記錄進行快速排序,遞歸該過程,直到序列中的所有記錄均有序為止。
package sorting; /** * 快速排序 * 平均O(nlogn),最好O(nlogn),最壞O(n^2);空間復雜度O(nlogn);不穩定;較復雜 * @author zeng * */ public class QuickSort { public static void sort(int[] a, int low, int high) { if(low>=high) return; int i = low; int j = high; int key = a[i]; while (i < j) { while (i < j && a[j] >= key) j--; a[i++] = a[j]; while (i < j && a[i] <= key) i++; a[j--] = a[i]; } a[i] = key; sort(a,low,i-1); sort(a,i+1,high); } public static void quickSort(int[] a) { sort(a, 0, a.length-1); for(int i:a) System.out.print(i+" "); } public static void main(String[] args) { int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 }; quickSort(a); } }