标签:堆排序
一、概念
堆排序是利用堆这种数据结构的性质设计的一种排序方式。
堆是一个近似完全二叉树的结构,并满足性质:子节点的键值或则索引值总是小于等于(或则大于等于)父节点的。
是不稳定排序。
二、原理
1.首先将待排序的数组进行堆化,构建成堆结构
2.将堆首和堆尾进行交换
3.将堆大小减一,并调整剩下的数据,将数组顶端数据调整到合适的位置,保证依然保证是堆的结构
4.重复2、3,直到大小为1,此时数据已经有序
三、复杂度
时间复杂度:O(nlog(n))
空间复杂度:O(1)
四、原理图
五、代码实现
//从root位置开始向下调整,数组长度为size
void heap_adjust(int arr[], int root, int size)
{
int left_child;
int key;
key = arr[root];
left_child = 2 * root + 1;
while (left_child < size) {
if ((left_child + 1 < size) && (arr[left_child + 1] > arr[left_child])) {
left_child++;
}
if (arr[left_child] <= key) {
break;
}
arr[root] = arr[left_child];
root = left_child;
left_child = 2 * root + 1;
}
arr[root] = key;
}
//将待排序数组进行堆化
void build_heap(int arr[], int size)
{
int index;
for (index = size / 2; index >= 0; index--) {
heap_adjust(arr, index, size);
}
}
//用于交换两个数(用异或只适用整数)
void swap(int *x, int *y)
{
*x = *x ^ *y;
*y = *x ^ *y;
*x = *x ^ *y;
}
//堆排序主函数
void heap_sort(int arr[], int size)
{
int index;
build_heap(arr, size);
for (index = size - 1; index >= 1; index--) {
swap(&arr[0], &arr[index]);
heap_adjust(arr, 0, index);
}
}标签:堆排序
原文地址:http://happytree007.blog.51cto.com/6335296/1690282