思想:
对全部元素n-1建立大顶堆后,将顶与最后一个元素交换;
而后对n-2个元素建堆,将顶与倒数第二个元素交换;
直到最后两个元素建堆。
C代码
#include "stdio.h"
void array_printf(int a[],int n);
void sort_heap(int a[],int n);
void build_heap(int a[],int e);
int main()
{
int i,a[] = {5,4,3,2,10,9,17,4,2,19,11};
int n = sizeof(a)/sizeof(int);
sort_heap(a,n);
array_printf(a,n);
return 0;
}
void array_printf(int a[],int n){
int i ;
for (i = 0; i < n; ++i)
{
printf("%d ",a[i]);
}
printf("\n");
}
void sort_heap(int a[],int n){
int i,x ;
for(i=n-1;i>0;i--){
build_heap(a,i);
x=a[0];
a[0] = a[i];
a[i] =x;
}
}
void build_heap(int a[],int e){
int r,i;
int x;
for(i=e;i>=1;i--){
r=(i-1)/2;
if(a[r]<a[i]){
x=a[r];
a[r] =a[i];
a[i] = x;
}
}
}
java代码
import java.util.List;
public class SortHeap implements Sort {
@Override
public void sort(List<Integer> source) {
for(int i = source.size()-1 ; i>0 ; i--){
build_heap(source, i);
switch_list_elements(source, 0, i);
}
}
private void build_heap(List<Integer> source, int e){
if(e>=source.size())
return;
for(int i = e; i>0 ; i--){
int root = (i-1)/2;
if(source.get(root)<source.get(i))
switch_list_elements(source, root, i);
}
}
private void switch_list_elements(List<Integer> source,int a, int b){
int x = source.get(a);
source.set(a, source.get(b));
source.set(b, x);
}
}