C语言实现八种基本排序(三)
2010-08-08 20:28
253 查看
heap_sort.c
#include <stdio.h> //the value of heapSize is belong 0 and (length - 1). int heapSize = 0; //get the left index of parent int Left(int parent) { return ((parent << 1) + 1); } //get the right index of parent int Right(int parent) { return ((parent << 1) + 2); } //exchange the two values void swap(int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; } //modify the heap and sign that the children of array[index] have been maxheaps. void maxHeapify(int *array, int parent) { int largest = parent; int left = Left(parent); int right = Right(parent); if((left <= heapSize) && (array[left] > array[largest])) largest = left; if((right <= heapSize) && (array[right] > array[largest])) largest = right; //at this time,array[largest] has been the max(array[left],array[right],array[index]) if(largest != parent) { swap(&array[parent], &array[largest]); maxHeapify(array, largest); } } //the arg len is the max valid index of array, not the real length of array. //the process to build a maxheap is to modify the heap until the index 0 is a maxheap from index ((index_len - 1) >> 1) void buildMaxHeap(int *array, int index_len) { int i; heapSize = index_len; for(i = ((index_len - 1) >> 1);i >= 0;i--) maxHeapify(array, i); } //the arg len is the real length of array void heap_sort(int array[], int len) { int i; //initialize the max heap buildMaxHeap(array, len - 1); for(i = (len - 1);i >= 1;i--) { //exchange the array[0] which is the max value to the end sequence zone. swap(&array[0], &array[i]); //change the size of unsequence zone. heapSize--; //rebuild the maxheap and at this time the children of array[0] are all maxheap, so modify the heap on index 0 only is OK. maxHeapify(array, 0); } } void print_array(int *a, int len) { int i; for(i = 0;i < len;i++) { printf("%d ", a[i]); } printf("/n"); } int main() { int a[] = {7,9,0,3,5,1,2,6,8,4}; print_array(a, 10); heap_sort(a, 10); print_array(a, 10); return 0; }
相关文章推荐
- C语言实现八种基本排序(四)
- C语言实现八种基本排序(一)
- C语言实现八种基本排序(二)
- C语言实现基本排序算法----排序(直接插入排序,SHELL排序,冒泡排序,快速排序,简单选择排序,堆排序)
- C语言提高-第26/27讲: 实现线性表基本操作的函数/编写查找和排序函数
- C语言基本排序算法之插入排序与直接选择排序实现方法
- 几种基本的排序算法(选择排序,冒泡排序,快速排序,归并排序,希尔排序)C语言实现
- java八种基本排序的实现
- 快速排序--C语言实现
- 排序(6)---------归并排序(C语言实现)
- c语言实现通讯录,包括增加名字,删除信息,查找,修改,排序
- C语言 链表的基本操作实现 源码
- C语言 指针方法实现三个数排序
- 学习笔记——线性表的动态分配顺序存储结构基本操作(C语言实现)
- 顺序存储结构线性表基本操作 纯C语言实现
- 快速排序的C语言实现
- 数据结构--单链表的基本操作(C语言实现)
- 【笔试面试知识点查缺补漏深入理解之C与C++篇】排序的C语言实现-插入-选择-快排
- 快速排序--C语言实现、python实现
- C语言实现栈的基本操作