public class Heap {
public static void main(String[] args) {
int size = 100000000;
int[] B = new int[size+1];
B[0] = size;
Random r = new Random();
for(int i = 1;i<=size;i++){
B[i]= r.nextInt();
}
HEAPSORT(B);
for(int i = 1;i<=B[0];i++){
System.out.print(B[i]+"\t");
}
System.out.println();
}
public static int PARENT(int i){
return i>>1;//计算父节点的下标
}
public static int LEFT(int i){
return i<<1;//计算左子节点的下标
}
public static int RIGHT(int i){
return (i<<1)+1;//计算右子节点的下标
}
public static void MAXHEAP(int[] A, int i, int heapSize){
int largest = i;
int l = LEFT(i);
int r = RIGHT(i);
if(l<=heapSize&&A[l]>A[largest]){//如果左节点比父节点大,则指向左节点
largest = l;
}
if(r<=heapSize&&A[r]>A[largest]){//如果右节点比父节点大,则指向右节点
largest = r;
}
if(largest!=i){//如果子节点的值比父节点大,则交换其值
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
MAXHEAP(A,largest,heapSize);//交换后的字节点可能违反最大堆的性质,递归的对子节点重新构建最大堆
}
}
public static void BUILDMAXHEAP(int[] A){
int heapSize = A[0];
for(int i = heapSize>>1;i>0;i--){//从第一个非叶子节点开始构建最大堆;
MAXHEAP(A,i,heapSize);
}
}
public static void HEAPSORT(int[] A){
BUILDMAXHEAP(A);
int heapSize = A[0];
while(heapSize>1){//将根节点的值与最后一个节点的值对调
int temp = A[1];
A[1] = A[heapSize];
A[heapSize] = temp;
heapSize--;//堆的大小-1
MAXHEAP(A,1,heapSize);
}
}
}
}
public static void main(String[] args) {
int size = 100000000;
int[] B = new int[size+1];
B[0] = size;
Random r = new Random();
for(int i = 1;i<=size;i++){
B[i]= r.nextInt();
}
HEAPSORT(B);
for(int i = 1;i<=B[0];i++){
System.out.print(B[i]+"\t");
}
System.out.println();
}
public static int PARENT(int i){
return i>>1;//计算父节点的下标
}
public static int LEFT(int i){
return i<<1;//计算左子节点的下标
}
public static int RIGHT(int i){
return (i<<1)+1;//计算右子节点的下标
}
public static void MAXHEAP(int[] A, int i, int heapSize){
int largest = i;
int l = LEFT(i);
int r = RIGHT(i);
if(l<=heapSize&&A[l]>A[largest]){//如果左节点比父节点大,则指向左节点
largest = l;
}
if(r<=heapSize&&A[r]>A[largest]){//如果右节点比父节点大,则指向右节点
largest = r;
}
if(largest!=i){//如果子节点的值比父节点大,则交换其值
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
MAXHEAP(A,largest,heapSize);//交换后的字节点可能违反最大堆的性质,递归的对子节点重新构建最大堆
}
}
public static void BUILDMAXHEAP(int[] A){
int heapSize = A[0];
for(int i = heapSize>>1;i>0;i--){//从第一个非叶子节点开始构建最大堆;
MAXHEAP(A,i,heapSize);
}
}
public static void HEAPSORT(int[] A){
BUILDMAXHEAP(A);
int heapSize = A[0];
while(heapSize>1){//将根节点的值与最后一个节点的值对调
int temp = A[1];
A[1] = A[heapSize];
A[heapSize] = temp;
heapSize--;//堆的大小-1
MAXHEAP(A,1,heapSize);
}
}
}
}