写了两种,中间用分割线隔开了,一种是基于partition的,方法名为sort0;一种是递归的,方法名为sort
public class QuickSort { public static void sort0(int[] a, int lo, int hi) { if(hi <= lo) return; int pivot = partition(a, lo, hi); sort(a, lo, pivot-1); sort(a, pivot+1, hi); } public static int partition(int[] a, int lo, int hi) { int pivot = a[lo], i=lo, j=hi+1; while (true) { while (a[++i] < pivot) if (i == hi) break; while (a[--j] > pivot) if (j == lo) break; if (i >= j) break; swap(a, i, j); } swap(a, lo, j); return j; } /*======================================分割线==================================================*/ public static void sort(int[] a, int lo, int hi) { if (hi <= lo) return; int lt = lo; int i = lo+1; int gt = hi; int v = a[lo]; while (i <= gt) { if (a[i] < v) swap(a, lt++, i++); else if (a[i] > v) swap(a, i, gt--); else i++; } sort(a, lo, lt - 1); sort(a, gt + 1, hi); } public static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } public static void main(String[] args) { int[] a = {7,5,3,60,78,6,43,4,3,67,2,5,6,23,6,2,6,75434,3,7,27,456,5,34,234}; //简单测试 sort(a, 0, a.length-1); System.out.println(Arrays.toString(a)); } }