快排的思想想必大家都懂,前后两个指针,向中间靠拢。我这个partition函数能保证所有相同的数都被比较一次,靠拢在一起。
代码:
public class Main { public static int[] partition1(int[] arr, int begin, int end, int pivotValue) { int small = begin-1; int cur = begin; int big = end+1; while(cur!=big) { if(arr[cur] < pivotValue) { swap(arr, ++small, cur++); } else if(arr[cur] > pivotValue) { swap(arr, cur, --big); } else { cur++; } } int[] range = new int[2]; range[0] = small; range[1] = big; return range; } public static void quickSort(int[] array,int low, int high) { if(array == null || array.length==0) { return; } if(low>=high) { return; } int[] res = partition1(array, low, high, array[low]); quickSort(array, low, res[0]); quickSort(array, res[1], high); } public static void main(String[] args) { int[] a = {34,2,25,1,12,34,12,56,23,15,34,12,12,54,34}; quickSort(a, 0, a.length-1); for(int i=0; i