package 排序算法;
public class 堆排序 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int [] a= {11,3,5,7,9,2,4,26,8,10};
show(a);
heapsort(a);
show(a);
}
public static void show(int []a)
{
for(int i:a)
{
System.out.print(i+" ");
}
System.out.println();
}
public static void heapsort(int []a)
{
for(int j=a.length;j>2;j--)
{
for(int i=j;i>1;i--)
{
int parent = i/2; //parent表示双亲结点的位置,下标=位置-1
int child=i; //child表示孩子结点的位置,下标=位置-1
if(a[parent-1]<a[child-1]) {
int temp = a[parent-1];
a[parent-1] = a[child-1];
a[child-1] = temp;
}
}
//排完一轮后将最后一个和第一个交换
int t=a[j-1];
a[j-1] = a[0];
a[0] = t;
}
}
}
结果:
11 3 5 7 9 2 4 26 8 10
2 3 4 5 7 8 9 10 11 26