简介:首先,这里的代码需要自己给数值给值,当然也可以参考我的代码,进行理解代码的执行。
如果代码有哪里不对的地方,希望小伙伴私聊讨论。谢谢,我在这里谢过了各位网友。
代码部分:
package tm.mbzvip.encapsulation.demo0519;
public class Heapsort {
public static void swap(int [] arr,int a,int b){
int temp = arr[a];
arr[a]= arr[b];
arr[b] = temp;
}
public static void heapify(int [] tree,int n,int i){
int lchild = 2*i+1;
int rchild = 2*i+2;
int max = i;
if(i>n) {
return;
}
if((lchild tree[max])){
max = lchild;
}
if((rchild < n)&&(tree[rchild]>tree[max])){
max = rchild;
}
if(max!=i){
swap(tree,i,max);
heapify(tree,n,max);
}
}
public static void createmaxheap(int [] tree,int n){
int i,lastnode = n -1;
int parent = (lastnode-1)/2;
for(i = parent;i>=0;i--){
heapify(tree,n,i);
}
}
public static void heapsort(int [] tree,int n){
createmaxheap(tree, n);
int i;
for(i = n-1;i>=0; i--)
{
swap(tree,0,i);
heapify(tree,i,0);
}
}
public static void main(String[] args) {
int [] tree = {3,7,2,9,8};
int n = tree.length;
//heapify(tree,n,0);
heapsort(tree,n);
for (int i = 0; i < tree.length; i++) {
System.out.println(tree[i]+" ");
}
}
}
代码运行部分:



