public class AlmostHeapSort
1: import java.util.ArrayList;
2: import java.util.Arrays;
3: import java.util.List;
4: import java.util.PriorityQueue;
6: /**
7: * A program to demonstrate an obvious sorting method -- loading elements into a
8: * heap and then pulling them out again in order from smallest to largest.
9: *
10: * @author Mark Young (A00000000)
11: */
12: public class AlmostHeapSort {
14: /**
15: * @param args the command line arguments
16: */
17: public static void main(String[] args) {
18: List<Integer> numbers =
19: new ArrayList<>(Arrays.asList(12, 4, 5, 10, 88, 23, 42, 10));
20: System.out.println("Before sorting: " + numbers);
21: almostHeapSort(numbers);
22: System.out.println("After sorting: " + numbers);
23: }
24:
25: /**
26: * Sort the elements of the given list by adding all its elements to a heap
27: * then putting them back into the list in the order the heap removes them.
28: *
29: * @param numbers the list to sort
30: */
31: private static void almostHeapSort(List<Integer> numbers) {
32: PriorityQueue<Integer> pq = new PriorityQueue<>();
33: pq.addAll(numbers);
34: numbers.clear();
35: while (!pq.isEmpty()) {
36: numbers.add(pq.remove());
37: }
38: }
40: }