算法步驟:java
1 從數組中挑出一個元素,稱爲 「基準」(pivot),如下實例取第一位數組元素爲基準數算法
2 從新排序數列,全部元素比基準值小的擺放在基準前面,全部元素比基準值大的擺在基準的後面(相同的數能夠到任一邊)。在這個分區退出以後,該基準就處於數列的中間位置。這個稱爲分區(partition)操做。數組
3 遞歸地(recursive)把小於基準值元素的子數列和大於基準值元素的子數列排序。ui
public static void quickSort(int[] elements) { System.out.println("elements="+Arrays.toString(elements)); System.out.println("------------------------------------------------"); split(elements, 0, elements.length-1); } private static void split(int[] elements, int left, int right) { int baseElement = elements[left];// 基準數 int l = left;// 記錄左邊的指針位置 int r = right;// 記錄右邊的指針位置 int temp = 0; boolean isSmallest = false;// 基準數是數組指定區域內最小的元素標誌 while(l != r) { while(l<r && elements[r] >= baseElement) { --r; } if(l == r) { isSmallest = true; break ; } while(l<r && elements[l] <= baseElement) { ++l; } if(l == r) { temp = elements[r]; elements[r] = baseElement; elements[left] = temp; split(elements, left, r-1); split(elements, l+1, right); } else { temp = elements[l]; elements[l] = elements[r]; elements[r] = temp; } } if(isSmallest) { split(elements, left+1, right); } System.out.println("elements="+Arrays.toString(elements)); System.out.println("------------------------------------------------"); }
調用方法:指針
public static void main(String[] args) { int[] array = {82 ,31 ,29 ,71, 72, 42, 64, 5, 110}; quickSort(array); }
執行結果:code
elements=[82, 31, 29, 71, 72, 42, 64, 5, 110] ------------------------------------------------ elements=[5, 29, 31, 71, 72, 42, 64, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------
參考頁面:htm