# 堆排序

package Sort;

public class Heap_Sort {
static int heap_length ;
public static void main(String[] args) {
int []a = {16,14,10,8,7,9,3,2,4,1};
int []b = new int [a.length+1];
for(int i =0;i<a.length;i++){
b[i+1] = a[i];
}
a = b;
//      heap_length = a.length-1;
ShowArray(a);
HEAPSORT(a);
ShowArray(a);
}
//显示数组
public static void ShowArray(int[]A){
for(int i=1;i<A.length;i++){
System.out.print(A[i]+" ");
}
System.out.println();
}

public static int PARENT(int i){//返回父节点
return i/2;
}

public static int LEFT(int i){//返回左节点
return i*2;
}

public static int RIGHT(int i){//返回右节点
return  i*2+1;
}

public static void MAX_HEAPIFY(int []A, int i){//堆的维护
int l = LEFT(i);
int r = RIGHT(i);
int largest;
//比较父节点，左右子节点大小
if(l<= heap_length && A[l]>A[i]){
largest = l;
}else{
largest = i;
}
if(r<=heap_length && A[r]>A[largest]){
largest = r;
}
//如果子节点比父节点大，则交换
if(largest != i){
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
MAX_HEAPIFY(A, largest);
}
}
/**
* 建堆
* @param A
*/
public static void BUILD_MAX_HEAP(int []A){
heap_length = A.length-1;
for(int i = heap_length/2;i>=1;i--){//维护最小父节点
MAX_HEAPIFY(A, i);
}
}
public static void HEAPSORT(int []A){
BUILD_MAX_HEAP(A);//建堆
for(int i = heap_length;i>1;i--){
int temp = A[1];
A[1] = A[i];
A[i] = temp;
heap_length--;
MAX_HEAPIFY(A, 1);
}
}
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：堆排序 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)