-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathHeapSort.java
45 lines (39 loc) · 841 Bytes
/
HeapSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Copyright 2022 jingedawang
*/
package sort;
import container.BinaryHeap;
import utils.ArrayPrinter;
import utils.ArrayGenerator;
/**
* Heap sort algorithm.
*
* This sort algorithm is implemented with {@link BinaryHeap}.
*/
public class HeapSort implements Sort {
/**
* Demo code.
*/
public static void main(String[] args) {
int[] arr = ArrayGenerator.fixedArray();
System.out.println("Original array:");
ArrayPrinter.print(arr);
Sort sort = new HeapSort();
sort.sort(arr);
System.out.println();
System.out.println("Sorted by heap sort:");
ArrayPrinter.print(arr);
}
/**
* Heap sort.
*
* @param arr Integer array to be sorted.
*/
@Override
public void sort(int[] arr) {
BinaryHeap heap = new BinaryHeap(arr, true);
for (int i = 0; i < arr.length; i++) {
arr[i] = heap.pop();
}
}
}