-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
40 lines (34 loc) · 745 Bytes
/
Copy pathHeapSort.java
File metadata and controls
40 lines (34 loc) · 745 Bytes
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
package sort;
import Util.Util;
public class HeapSort {
public int[] sort(int[] a)
{
for(int i = a.length/2-1;i>=0;i--)
{
HeapAdjust(a,i,a.length-1);
}
for(int i = a.length-1;i>=0;i--)
{
Util.swap(a,0,i);
HeapAdjust(a,0,i-1);
}
return a;
}
public void HeapAdjust(int[] a,int l,int h)
{
int temp = a[l];
for(int j = 2*l+1;j<=h;j=j*2+1)//得到子节点的最大值
{
if(j+1 <=h && a[j] < a[j+1])
{
j++;
}
if(temp < a[j])
{
a[l] = a[j];
l = j;
}
}
a[l] = temp;
}
}