• Welcome to the world's largest Chinese hacker forum

    Welcome to the world's largest Chinese hacker forum, our forum registration is open! You can now register for technical communication with us, this is a free and open to the world of the BBS, we founded the purpose for the study of network security, please don't release business of black/grey, or on the BBS posts, to seek help hacker if violations, we will permanently frozen your IP and account, thank you for your cooperation. Hacker attack and defense cracking or network Security

    business please click here: Creation Security  From CNHACKTEAM

堆排序(以小顶堆为例,用大顶堆结果才是递增)分为两步:堆化、按序输出


Recommended Posts

包演示;

导入Java。util。数组;

公共类P47 {

//堆必定是完全二叉树,小顶堆任意父节点小于等于其子节点,大顶堆则是大于等于

//堆排序(以小顶堆为例,用大顶堆结果才是递增)分为两步:堆化、按序输出

//堆化:从倒数第二行有子节点的父节点((n-1)/2)倒数,挨个调整到符合小顶堆

//按序输出:把堆顶和最后一个元素交换,然后(堆范围-1)重新调整,完成后堆中就是递减

公共静态void main(String[] args) {

int[] arr={9,7,2,3,5,6,4 };

//makeMinHeap(arr,arr。长度-1);

//系统。出去。println(数组。tostring(arr));

堆排序(数组,数组。长度-1);

系统。出去。println(数组。tostring(arr));

}

静态void makeMinHeap(int[] arr,int n) {

for(int I=(n-1)/2;I=0;我- ) {

fixMinHeap(arr,n,I);

}

}

静态void fixMinHeap(int[] arr,int n,int i) {

//i,j,k分别为父、左、右下标

int j=2 * I 1;

int k=j 1;

int smaller=j;

int iValue=arr

while(j=n) {//有叶结点

if(kn) {//只有左

if(arr=arr[j]) {

返回;

}否则{

arr=arr[j];

arr[j]=iValue;

fixMinHeap(arr,n,j);

返回;

}

}

//左右都有

if(arr[k]arr[j]) {//左右哪个更小

更小;

}

if(arr=arr[small]){

返回;

}否则{

arr=arr[small];

arr[small]=iValue;

fixMinHeap(arr,n,较小);

}

}

}

静态空的堆排序(int[] arr,int n) {

makeMinHeap(arr,n);

内部温度;

for(int I=n;I=1;我- ) {

temp=arr[0];

arr[0]=arr

arr=temp;

fixMinHeap(arr,i-1,0);//堆范围-1,从根节点再次调整

}

}

}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now