我从:algorithms/Heapsort#C找到了堆排序的代码
我理解它的方式(在某些方面是错误的)是heapsort()函数有两个循环。第一个循环是创建堆结构( min或max),第二个循环是实际对双重进行排序。但我想我的第一个循环出了问题。
整个代码是这样的
#include <stdio.h>
#include <stdlib.h>
#define ValType double
#define IS_LESS(v1, v2) (v1 < v2)
void siftDown( ValType *a, int start, int count);
#define SWAP(r,s) do{ValType t=r; r=s; s=t; } while(0)
void heapsort( ValType *a, int count)
{
int start, end;
/* heapify */
for (start = (count-2)/2; start >=0; start--) {
siftDown( a, start, count);
}
for (end=count-1; end > 0; end--) {
SWAP(a[end],a[0]);
siftDown(a, 0, end);
}
}
void siftDown( ValType *a, int start, int end)
{
int root = start;
while ( root*2+1 < end ) {
int child = 2*root + 1;
if ((child + 1 < end) && IS_LESS(a[child],a[child+1])) {
child += 1;
}
if (IS_LESS(a[root], a[child])) {
SWAP( a[child], a[root] );
root = child;
}
else
return;
}
}
int main()
{
int ix;
double valsToSort[] = {
1.4, 50.2, 5.11, -1.55, 301.521, 0.3301, 40.17,
-18.0, 88.1, 30.44, -37.2, 3012.0, 49.2};
#define VSIZE (sizeof(valsToSort)/sizeof(valsToSort[0]))
heapsort(valsToSort, VSIZE);
printf("{");
for (ix=0; ix<VSIZE; ix++) printf(" %.3f ", valsToSort[ix]);
printf("}\n");
return 0;
}我的问题是,为什么/heapify/循环开始于(count-2)/2?
来自heapsort()的代码片段如下:
/* heapify */
for (start = (count-2)/2; start >=0; start--) {
siftDown( a, start, count);
}更新
我想我可能已经回答了我自己的问题,但这是不是因为我们必须建立一个堆结构,循环的部分重点是创建一个平衡的树?也就是说,除了最后一层外,堆必须填满所有级别。这个想法正确吗?
发布于 2015-12-05 22:07:53
对于奇数,用于堆化的第一对子对是( count - 2 )/2)*2+1和(count-2)/2)*2+2),这是数组的最后两个元素。对于偶数,单独的子元素位于(( count -2)/2)*2+ 1,这是数组的最后一个元素。这是对整个数组进行堆堆的起点。第二个循环只需要重新堆一个大部分堆积的array0,就可以以结束下降结束。
Wiki文章:
http://en.wikipedia.org/wiki/Heapsort
https://stackoverflow.com/questions/34111120
复制相似问题