#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 11
struct heap{
int arr[N];
int length;
int heapSize;
};
int parent(int i){ // parent node
return i>>1;
}
int left(int i){ // left child
return i<<1;
}
int right(int i){ // right child
return (i<<1) +1;
}
void exchange(int *a, int *b){ // exchange function for c language
int temp = *a;
*a = *b;
*b = temp;
}
/**
* maxHeapify is an important subroutine for manipulating heaps.
* When maxHeapify is called, it is assumed that the binary trees
* rooted at left(i) and right(i) are heaps, but that value of a node of i
* may be small than its children.
* the running time of maxHeapify on a node of height h is O(h)
**/
int maxHeapify(struct heap* maxHeap, int i){ //
int l = left(i);
int r = right(i);
int largest = i;
//the index of the largest of the three elements is stored in var largest.
if(maxHeap->heapSize>=l && maxHeap->arr[l]>maxHeap->arr[largest]){
largest = l;
}
if(maxHeap->heapSize>=r && maxHeap->arr[r]>maxHeap->arr[largest]){
largest = r;
}
if(largest != i){
exchange(&maxHeap->arr[largest], &maxHeap->arr[i]);
//the subtree rooted at largest may violate the heap property
//so,maxHeapify() must be called recursively on that subtree.
maxHeapify(maxHeap, largest);
}
// for(int i=1; i<=maxHeap->heapSize; ++i){
// printf("%d ", maxHeap->arr[i]);
// }
// printf("\n");
}
/**
* use the procedure maxHeapify in a bottom-up manner
* to convert an array into a heap.
* the running time is O(n).
* Hence, we can build a heap form an unordered array in linear time.
**/
void bulidMaxHeap(struct heap* maxHeap){
maxHeap->heapSize = maxHeap->length;
for(int i=maxHeap->length/2; i>0; --i)
maxHeapify(maxHeap, i);
}
/**
* the heapsort algorithm.
* the running time is O(nlg n).
**/
void heapSort(struct heap* maxHeap){
bulidMaxHeap(maxHeap);
// for(int i=1; i<=maxHeap->length; ++i){
// printf("%d ", maxHeap->arr[i]);
// }
for(int i=maxHeap->length; i>1; --i){
exchange(&maxHeap->arr[1], &maxHeap->arr[i]);
maxHeap->heapSize--;
maxHeapify(maxHeap, 1);
}
}
int main()
{
struct heap myHeap = {
{0, 16, 4, 10, 14, 7, 9, 3, 2, 8, 1}, N-1, 10
};
struct heap myHeap2 = {
{0, 4, 1, 3, 2, 16, 9, 10, 14, 8, 7}, N-1, 10
};
//maxHeapify(&myHeap,2);
//bulidMaxHeap(&myHeap2);
heapSort(&myHeap2);
for(int i=1; i<=myHeap2.length; ++i){
printf("%d ", myHeap2.arr[i]);
}
return 0;
}
the heapsort algorithm
最新推荐文章于 2022-02-23 14:49:40 发布