笔记笔记!以后直接用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEFT(i) ((i)<<1)
#define RIGHT(i) ((i)<<1|1)
void Swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void Max_Heap(int *A, int i, int n)
{
int l = LEFT(i);
int r = RIGHT(i);
int largest;
if(l <= n && A[l] > A[i])
largest = l;
else largest = i;
if(r <= n && A[r] > A[largest])
largest = r;
if(largest != i){
Swap(&A[i], &A[largest]);
Max_Heap(A, largest, n);
}
}
void Build_Max_Heap(int *A, int n)
{
int i;
for(i=n/2; i>0; i--){
Max_Heap(A, i, n);
}
}
void Heap_Sort(int *A, int n)
{
Build_Max_Heap(A, n);
int i;
for(i=n; i>=2; i--){
Swap(&A[i], &A[1]);
n--;
Max_Heap(A, 1, n);
}
}
int main()
{
int a[] = {-1, 3, 2, 6, 4, 5, 7, 5, 8, 1, 9, 0};//下标1~11为待排序元素
Heap_Sort(a, 11);
int i;
for(i=1; i<12; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}