標籤:pac 截取 過程 i++ res static lan 選擇 .so
java實現一個快速排序的演算法,用nio裡的IntBuffer實現,
IntBuffer提供了slice,position,capacity等方法可以很方便的操縱數組.用來做排序很是方便.
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通過一趟排序將要排序的資料分割成獨立的兩部分,其中一部分的所有資料都比另外一部分的所有資料都要小,然後再按此方法對這兩部分資料分別進行快速排序,整個排序過程可以遞迴進行,以此達到整個資料變成有序序列。
1 public class QuickSort { 2 3 static void sort(IntBuffer items, IntBuffer resultItems) { 4 if (items.capacity() == 1) { // 拆分到只剩1個元素時停止迭代,儲存資料到結果隊列 5 resultItems.put(items.get()); 6 return; 7 } 8 int midPos = items.capacity() / 2; // 從數組的中間選擇一個數進行二分 9 int midValue = items.get(midPos);10 IntBuffer lowItems = IntBuffer.allocate(items.capacity());11 IntBuffer highItems = IntBuffer.allocate(items.capacity());12 for (int i = 0; i < items.capacity(); i++) {13 if (i == midPos)14 continue;// 跳過自己15 int curValue = items.get(i);16 if (curValue <= midValue) {17 lowItems.put(curValue);18 } else {19 highItems.put(curValue);20 }21 }22 // 把選的比較數放入較小的集合中,防止死迴圈23 if (lowItems.position() < highItems.position())24 lowItems.put(midValue);25 else26 highItems.put(midValue);27 lowItems.flip();// 截取有效資料28 lowItems = lowItems.slice();29 highItems.flip();30 highItems = highItems.slice();// 截取有效資料31 if (lowItems.capacity() > 0) {32 QuickSort.sort(lowItems, resultItems);33 }34 if (highItems.capacity() > 0) {35 QuickSort.sort(highItems, resultItems);36 }37 }38 39 public static void main(String[] agrs) {40 IntBuffer sourceItems = IntBuffer.wrap(new int[] { 5, 2, 10, 1, 3, 8, 5, 6, 1 });41 IntBuffer resultItems = IntBuffer.allocate(sourceItems.capacity());42 QuickSort.sort(sourceItems, resultItems);43 System.out.println(Arrays.toString(resultItems.array()));44 }45 }
java 快速排序 ,用nio裡的IntBuffer實現,