java 快速排序 ,用nio裡的IntBuffer實現,

來源:互聯網
上載者:User

標籤: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實現,

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.