#include <stdio.h>
#include <stdlib.h>
/*
MAX-HEAPIFY(A, i) //保持最大堆
1 l ← LEFT(i)
2 r ← RIGHT(i)
3 if l ≤ heap-size[A] and A[l] > A[i]
4 then largest ← l
5 else largest ← i
6 if r ≤ heap-size[A] and A[r] > A[largest]
7 then largest ← r
8 if largest ≠ i
9 then exchange A[i] <-> A[largest]
10 MAX-HEAPIFY(A, largest)
*/
void maxheap(int A[], int len, int i)
{
int l = 2*i+1;
int r = 2*i+2;
int largest = i;
if(l < len && A[l] > A[i])
largest = l;
else
largest = i;
if(r < len && A[r] > A[largest])
largest = r;
if (largest != i){
int tmp = A[largest];
A[largest] = A[i];
A[i] = tmp;
maxheap(A, len, largest);
}
}
void minheap(int A[], int len, int i)
{
int l = 2*i+1;
int r = 2*i+2;
int smallest = i;
if(l < len && A[l] < A[i])
smallest = l;
else
smallest = i;
if(r < len && A[r] < A[smallest])
smallest = r;
if (smallest != i){
int tmp = A[smallest];
A[smallest] = A[i];
A[i] = tmp;
minheap(A, len, smallest);
}
}
/*
BUILD-MAX-HEAP(A) //建堆
1 heap-size[A] ← length[A]
2 for i ← |_length[A]/2_| downto 1
3 do MAX-HEAPIFY(A, i)
*/
void buildheap(int A[], int len)
{
int heapsize = len;
for(int i = len/2-1; i >=0; i--)
//maxheap(A,len,i);
minheap(A,len,i);
}
/*
HEAPSORT(A) //n-1次调用MAX-HEAPIFY,所以,O(n*lgn)
1 BUILD-MAX-HEAP(A) //建最大堆,O(n)
2 for i ← length[A] downto 2
3 do exchange A[1] <-> A[i]
4 heap-size[A] ← heap-size[A] - 1
5 MAX-HEAPIFY(A, 1) //保持堆的性质,O(lgn)
*/
void heapsort(int A[], int len)
{
buildheap(A,len);
for(int i = len-1; i>=1; i--){
int tmp = A[0];
A[0] = A[i];
A[i] = tmp;
len = len-1;
minheap(A,len,0);
}
}
int main()
{
int A[] = {1,5,4,7,9,2,3,6,8};
int len = sizeof(A)/sizeof(A[0]);
for(int i = 0; i < len ; i++)
printf("%d ", A[i]);
printf("\n");
//buildheap(A,len);
heapsort(A,len);
for(int i = 0; i < len ; i++)
printf("%d ", A[i]);
printf("\n");
return 1;
}
网友评论