堆排序
堆排序
感觉。。不如快排
#include<stdio.h>
void adjust_max_heap(int* arr, int adjust_pos, int len)
{
int dad = adjust_pos;
int son = 2 * dad + 1;
while (son < len)
{
if (son + 1 < len && arr[son] < arr[son + 1])
{
son++;
}
if (arr[son] > arr[dad])
{
int temp;//若孩子大于父亲,则交换
temp = arr[son];
arr[son] = arr[dad];
arr[dad] = temp;
dad = son;//验证新的孩子节点是否满足
son = dad * 2 + 1;
}
else
{
break;
}
}
}
void heap_sort(int* arr)
{
for (int i = 10 / 2 - 1; i >= 0; i--)//初始化大根堆
{
adjust_max_heap(arr, i, 10);
}
int temp;//将最大元素转移至末尾
temp = arr[0];
arr[0] = arr[10 - 1];
arr[10 - 1] = temp;
for (int i = 10 - 1; i > 1; i--)
{
adjust_max_heap(arr, 0, i);
temp = arr[0];
arr[0] = arr[i - 1];
arr[i - 1] = temp;
}
}
int main()
{
int arr[10] = { 9,3,5,7,1,2,4,6,8,0 };
heap_sort(&arr);
}