Heap sorting tool class (applicable to top k problems, java generic implementation) and heap sorting tool class
The Code is as follows:
1 public class HeapSort {2 // method function: retrieve the minimum k values in the list. 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 must be greater than 0"); 6} 7 if (list. size () <k) {8 throw new Exception ("list length must be greater than 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 stat Ic <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 ). c OmpareTo (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}