-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
59 lines (48 loc) · 1.08 KB
/
Copy pathHeapSort.java
File metadata and controls
59 lines (48 loc) · 1.08 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package sortAlgorithm;
public class HeapSort {
public static void main(String[] args)
{
int[] arr = {1,3,5,7,8,6,4,2};
ArrayUtils.printArray(arr);
System.out.println();
heapSort(arr);
ArrayUtils.printArray(arr);
}
public static void heapSort(int[] arr)
{
int len = arr.length;
if(arr == null || len <= 1)
return;
buildMaxHeap(arr);//构建最大堆
for(int i = len-1;i >= 1;--i)
{
ArrayUtils.exchange(arr, 0, i); //
maxHeap(arr,i,0);
}
}
public static void buildMaxHeap(int[] arr)
{
if(arr == null || arr.length <= 1)
return;
int half = arr.length / 2;
for(int i = half;i >= 0;--i)
{
maxHeap(arr,arr.length,i);
}
}
public static void maxHeap(int[] arr,int heapSize,int index)
{
int left = 2 * index + 1;
int right = 2 * index + 2;
int largest = index;
if(left < heapSize && arr[left] > arr[largest])
largest = left;
if(right < heapSize && arr[right] > arr[largest])
largest = right;
if(largest != index)
{
ArrayUtils.exchange(arr, index, largest);
maxHeap(arr, heapSize, largest);
}
}
}