快排的核心是partition函数。主要思路是,随机找一个值,然后遍历数组,大于该值的放在该值的右边,小于该值的放在该值的左侧。
algorithm quicksort(A, lo, hi) is if lo < hi then p := partition(A, lo, hi) quicksort(A, lo, p - 1) quicksort(A, p + 1, hi) algorithm partition(A, lo, hi) is pivot := A[hi] i := lo for j := lo to hi do if A[j] < pivot then swap A[i] with A[j] i := i + 1 swap A[i] with A[hi] return i
public class QuickSort { public static void quickSort(int [] arr,int left,int right) { int pivot=0; if(left<right) { pivot=partition(arr,left,right); quickSort(arr,left,pivot-1); quickSort(arr,pivot+1,right); } } private static int partition(int[] arr,int left,int right) { int key=arr[left]; while(left<right) { while(left<right && arr[right]>=key) { right--; } arr[left]=arr[right]; while(left<right && arr[left]<=key) { left++; } arr[right]=arr[left]; } arr[left]=key; return left; } public static void main(String[] args) { int arr[]= {65,58,95,10,57,62,13,106,78,23,85}; System.out.println("排序前:"+Arrays.toString(arr)); quickSort(arr,0,arr.length-1); System.out.println("排序后:"+Arrays.toString(arr)); } }