The code is as follows, as described in the title
1 Public classHeapsort {2 //method: Take out the smallest k value inside the list3 Public Static<textendscomparable<t>> list<t> Sort (list<t> List,intKthrowsException {4 if(k <= 0) {5 Throw NewException ("K must be greater than 0");6 }7 if(List.size () <k) {8 Throw NewException ("list length must be greater than K");9 }TenList<t> heaplist =NewArraylist<t>(k); One for(inti = 0; I < K; i + +) { A Heaplist.add (List.get (i)); - } - initialheap (heaplist); the for(inti = k; I < list.size (); i + +) { - if(List.get (i). CompareTo (heaplist.get (0)) < 0) { -Heaplist.set (0, List.get (i)); -Heapify (heaplist, K, 0); + } - } + returnheaplist; A } at Private Static<textendsComparable<t>>voidInitialheap (list<t>list) { - intn =list.size (); - //Build heap (rearrange array) - for(inti = N/2-1; I >= 0; i--) - heapify (list, n, i); - } in Private Static<textendsComparable<t>>voidHeapify (list<t> List,intNinti) - { to intlargest = i;//Initialize largest as root + intL = 2*i + 1;//Left = 2*i + 1 - intr = 2*i + 2;//Right = 2*i + 2 the * //If left child is larger than root $ if(L < n && (List.get (L). CompareTo (List.get (largest)) > 0))Panax Notoginsenglargest =l; - the //If right child are larger than largest so far + if(R < n && (List.get (R). CompareTo (List.get (largest)) > 0)) Alargest =R; the + //If largest is not root - if(Largest! =i) $ { $T swap =List.get (i); - List.set (i, List.get (largest)); - List.set (largest, swap); the //recursively heapify the affected sub-tree - heapify (list, n, largest);Wuyi } the } -}
Heap Sort Tool Class (for top k problem, Java generic implementation)