堆排序工具類(適用於top k問題,java泛型實現)

來源:互聯網
上載者:User

標籤:class   sort   add   return   堆排序   throw   工具類   size   compareto   

代碼如下,作用如標題所述

 1 public class HeapSort { 2     //方法作用:取出list裡面的最小的 k 個值 3     public static <T extends Comparable<T>> List<T> sort(List<T> list, int k) throws Exception { 4         if (k <= 0) { 5             throw new Exception("k 必須大於0"); 6         } 7         if (list.size() < k) { 8             throw new Exception("list 長度必須大於k"); 9         }10         List<T> heapList = new ArrayList<T>(k);11         for (int i = 0; i < k; i ++) {12             heapList.add(list.get(i));13         }14         initialHeap(heapList);15         for (int i = k; i < list.size(); i ++) {16             if (list.get(i).compareTo(heapList.get(0)) < 0) {17                 heapList.set(0, list.get(i));18                 heapify(heapList, k, 0);19             }20         }21         return heapList;22     }23     private static <T extends Comparable<T>> void initialHeap(List<T> list) {24         int n = list.size();25         // Build heap (rearrange array)26         for (int i = n / 2 - 1; i >= 0; i--)27             heapify(list, n, i);28     }29     private static <T extends Comparable<T>> void heapify(List<T> list, int n, int i)30     {31         int largest = i;  // Initialize largest as root32         int l = 2*i + 1;  // left = 2*i + 133         int r = 2*i + 2;  // right = 2*i + 234 35         // If left child is larger than root36         if (l < n && (list.get(l).compareTo(list.get(largest)) > 0))37             largest = l;38 39         // If right child is larger than largest so far40         if (r < n && (list.get(r).compareTo(list.get(largest)) > 0))41             largest = r;42 43         // If largest is not root44         if (largest != i)45         {46             T swap = list.get(i);47             list.set(i, list.get(largest));48             list.set(largest, swap);49             // Recursively heapify the affected sub-tree50             heapify(list, n, largest);51         }52     }53 }

 

堆排序工具類(適用於top k問題,java泛型實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.