// heap_sort.h
// 大堆排序
#ifndef _HEAP_SORT_H_
#define _HEAP_SORT_H_
#include "utility.h"
/* 左节点 */
int tree_left(int i)
{
return 2 * i + 1;
}
/* 右节点 */
int tree_right(int i)
{
return (2 * i + 2);
}
/* 以第i点为根节点,调整为大堆树 */
void max_heapify(int arr[], int i, int heap_size)
{
int left = tree_left(i);
int right = tree_right(i);
int largest = i;
int tmp;
/* 搜索最大节点 */
if (left <= heap_size && arr[left] > arr[i])
largest = left;
if (right <= heap_size && arr[right] > arr[left])
largest = right;
/* 交换节点, 递归*/
if (largest != i) {
tmp = arr[i];
arr[i] = arr[largest];
arr[largest] = tmp;
max_heapify(arr, largest, heap_size);
}
}
/* 获取大堆树 */
void build_max_heap(int arr[], int len)
{
for (int i=len/2; i>=0; i--)
max_heapify(arr, i, len);
}
/* 堆排序 */
void heap_sort(int arr[], int len)
{
build_max_heap(arr, len-1);
print_arr(arr, len);
int tmp;
for(int i = len-1; i > 0; i--)
{
tmp = arr[0];
arr[0] = arr[i];
arr[i] = tmp;
max_heapify(arr, 0, i-1);
}
print_arr(arr, len);
}
/* 测试 */
void test_heap_sort()
{
//int arr[] = {4, 5, 1, 8, 6};
int arr[] = {4, 5, 1, 8, 6, 38, 7, 19, 9, 12, 17, 33, 25, 68, 90};
int len = ARR_SIZE(arr);
heap_sort(arr, len);
}
#endif
// heap_sort.h
// 小堆排序
#ifndef _HEAP_SORT_H_
#define _HEAP_SORT_H_
#include "utility.h"
/* 左节点 */
int tree_left(int i)
{
return 2 * i + 1;
}
/* 右节点 */
int tree_right(int i)
{
return (2 * i + 2);
}
/* 以第i点为根节点,调整为小堆树 */
void min_heapify(int arr[], int i, int heap_size)
{
int left = tree_left(i);
int right = tree_right(i);
int minimum = i;
int tmp;
/* 搜索最小节点 */
if (left <= heap_size && arr[left] < arr[i])
minimum = left;
if (right <= heap_size && arr[right] < arr[minimum])
minimum = right;
/* 交换节点, 递归*/
if (minimum != i) {
tmp = arr[i];
arr[i] = arr[minimum];
arr[minimum] = tmp;
min_heapify(arr, minimum, heap_size);
}
}
/* 获取小堆树 */
void build_min_heap(int arr[], int len)
{
for (int i=len/2; i>=0; i--)
{
min_heapify(arr, i, len);
}
}
/* 反转数组 */
void reverse_arr(int arr[], int len)
{
int tmp = 0;
for (int i=0; i<len/2; i++)
{
tmp = arr[i];
arr[i] = arr[len-1-i];
arr[len-1-i] = tmp;
}
}
/* 堆排序 */
void heap_sort(int arr[], int len)
{
build_min_heap(arr, len-1);
print_arr(arr, len);
int tmp;
for(int i = len-1; i > 0; i--)
{
tmp = arr[0];
arr[0] = arr[i];
arr[i] = tmp;
min_heapify(arr, 0, i-1);
}
reverse_arr(arr, len);
print_arr(arr, len);
}
/* 测试 */
void test_heap_sort()
{
//int arr[] = {4, 5, 1, 8, 6, 38, 7,};
int arr[] = {4, 5, 1, 8, 6, 38, 7, 19, 9, 12, 17, 33, 25, 68, 90};
int len = ARR_SIZE(arr);
heap_sort(arr, len);
}
#endif
参考
http://zh.wikipedia.org/wiki/%E5%A0%86%E6%8E%92%E5%BA%8F
http://en.wikipedia.org/wiki/Heapsort