MCPcopy Index your code
hub / github.com/hustcc/JS-Sorting-Algorithm / HeapSort

Class HeapSort

src/java/main/HeapSort.java:6–56  ·  view source on GitHub ↗

堆排序

Source from the content-addressed store, hash-verified

4 * 堆排序
5 */
6public class HeapSort implements IArraySort {
7
8 @Override
9 public int[] sort(int[] sourceArray) throws Exception {
10 // 对 arr 进行拷贝,不改变参数内容
11 int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
12
13 int len = arr.length;
14
15 buildMaxHeap(arr, len);
16
17 for (int i = len - 1; i > 0; i--) {
18 swap(arr, 0, i);
19 len--;
20 heapify(arr, 0, len);
21 }
22 return arr;
23 }
24
25 private void buildMaxHeap(int[] arr, int len) {
26 for (int i = (int) Math.floor(len / 2); i >= 0; i--) {
27 heapify(arr, i, len);
28 }
29 }
30
31 private void heapify(int[] arr, int i, int len) {
32 int left = 2 * i + 1;
33 int right = 2 * i + 2;
34 int largest = i;
35
36 if (left < len && arr[left] > arr[largest]) {
37 largest = left;
38 }
39
40 if (right < len && arr[right] > arr[largest]) {
41 largest = right;
42 }
43
44 if (largest != i) {
45 swap(arr, i, largest);
46 heapify(arr, largest, len);
47 }
48 }
49
50 private void swap(int[] arr, int i, int j) {
51 int temp = arr[i];
52 arr[i] = arr[j];
53 arr[j] = temp;
54 }
55
56}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected