动手实现 算法 之 “堆排序”
2015-05-09 23:27
148 查看
由于最小堆插入删除之后能够保持每个子节点都大于父节点,因此只要每次删除根节点(最小节点)就能够得到有序序列
#include <stdio.h> const long MaxSizeOfPile = 999; const long MaxNum = 9999; // The Min Pile struct Pile { int arr[MaxSizeOfPile]; int size; }; void InitPile(struct Pile * pile) { pile->size = 0; } void Insert(struct Pile * pile, int data) { int pos = pile->size+1; pile->arr[pos] = data; while(pile->arr[pos] < pile->arr[pos/2] && pos > 1) { int temp = pile->arr[pos]; pile->arr[pos] = pile->arr[pos/2]; pile->arr[pos/2] = temp; pos /= 2; } ++pile->size; } int Min(struct Pile * pile) { return pile->arr[1]; } int EraseMin(struct Pile * pile) { int result = pile->arr[1]; if(pile->size%2 == 0) { pile->arr[pile->size+1] = MaxNum; } int pos = 2, leaf = pos; while(pos <= pile->size) { if(pile->arr[pos] < pile->arr[pos+1]) { pile->arr[pos/2] = pile->arr[pos]; leaf = pos; } else { pile->arr[pos/2] = pile->arr[pos+1]; leaf = ++pos; } pos *= 2; } if(pile->size > 0) { pile->arr[leaf] = pile->arr[pile->size]; --pile->size; } return result; } int main(void) { const int N = 7; int a = {3, 10, 9, 11, 12, 5, 2}; struct Pile pile; InitPile(&pile); for(int i=0; i<N; i++) { Insert(&pile, a[i]); } for(int i=0; pile.size > 0; i++) { a[i] = EraseMin(&pile); } for(int i=0; i<N; i++) { printf("%d ", a[i]); } return 0; }
相关文章推荐
- java实现算法之堆排序
- 堆排序(Heap Sort)算法的实现
- 算法导论-----------堆排序研究 (堆排序原理及算法实现(最大堆))
- 计算机算法--最大堆实现堆排序(从大到小输出)
- 自主实现的Java实现的构造大小堆、堆排序的算法
- 算法设计之,堆,堆排序,基于最大堆的最大优先队列的实现(C++实现)
- 动手实现 算法 之 “希尔排序”
- 算法基础:堆排序原理及其实现
- c++模板类实现算法堆排序
- 堆排序的算法实现
- 基本算法-堆排序及其Java实现
- C语言对堆排序一个算法思路和实现代码
- 算法实现系列第二章.堆排序
- 排序(快排,冒泡,堆排序,插入排序,归并排序,选择排序)算法Java实现
- [算法练习]堆排序的C语言实现
- 算法代码实现之堆排序,Java实现
- 经典算法: 堆排序的原理和实现, 建立堆,调整堆
- 深入解析堆排序的算法思想及Java代码的实现演示
- 堆排序(Heap Sort) 算法实现 C语言版
- 排序算法(四)堆排序的Python实现及算法详解