* 快速排序使用分治法(Divide and conquer)策略來把一個序列(list)分爲兩個子序列(sub-lists)。java
* 步驟爲:app
* 從數列中挑出一個元素,稱爲"基準"(pivot),從新排序數列,全部元素比基準值小的擺放在基準前面,全部元素比基準值大的擺在基準的後面(相同的數能夠到任一邊)。ide
* 在這個分區結束以後,該基準就處於數列的中間位置。這個稱爲分區(partition)操做。ui
* 遞歸地(recursive)把小於基準值元素的子數列和大於基準值元素的子數列排序。spa
/** * * @author Administrator * */ public class QuickSort { public static void main(String[] args) { int number[] = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 }; compare(number,0,number.length-1); p(number); } private static void compare(int[] number, int left, int right) { if(right>left){ int pivotIndex = left; int pivotNewIndex = partition(number,left,right,pivotIndex); compare(number,left,pivotNewIndex-1); compare(number,pivotNewIndex+1,right); } } private static int partition(int[] number, int left, int right, int pivotIndex) { int pivotValue = number[pivotIndex]; swap(number,pivotIndex,right);//基數交換到最後位置 int storeIndex = left; for (int i = left; i < right; i++) { if(number[i]<pivotValue){ swap(number,storeIndex,i); storeIndex = storeIndex+1; } } swap(number,right,storeIndex); return storeIndex; } private static void swap(int number[],int index1,int index2 ) { int temp = number[index2]; number[index2] = number[index1]; number[index1] = temp; } private static void p(int num[]) { StringBuilder sb = new StringBuilder(num.length); for (int i = 0; i < num.length; i++) { sb.append(num[i]); sb.append(" "); } System.out.println(sb.toString()); } }