我在我的算法类中为分配实现 HeapSort,我终于完成了,但由于某种原因,排序跳过了我数组中的第一个元素。
原始数组:
int heapArray[SIZE] = { 5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
HeapSort() 之后的输出
5 99 32 15 13 12 8 4 1
我浏览了所有功能,但无法弄清楚为什么它会跳过第一个元素。谁能帮我吗?Iv 包括了下面的所有 HeapSort 函数。我知道它有很多值得一看的地方,但我太接近了。
int main()
{
int heapArray[SIZE] = { 5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
HeapSort(heapArray);
return 0;
}
..................................................... ……………………………………………………………………………………………………………………………………
void HeapSort(int heapArray[])
{
int heap_size = SIZE;
int n = SIZE;
int temp;
Build_Max_Heap(heapArray);
for(int i = n-1; i >= 2; i--)
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;
heap_size = heap_size-1;
Max_Heapify(heapArray,1);
}
return;
}
..................................................... .........................................................
void Build_Max_Heap(int heapArray[])
{
double n = SIZE;
for(double i = floor((n-1)/2); i >= 1; i--)
{
Max_Heapify(heapArray,i);
}
return;
}
..................................................... .........................................................
void Max_Heapify(int heapArray[],int i)
{
int n = SIZE;
int largest = 0;
int l = Left(i);
int r = Right(i);
if(( l <= n) && (heapArray[l] > heapArray[i]))
{
largest = l;
}
else
{
largest = i;
}
if( (r <= n) && ( heapArray[r] > heapArray[largest]))
{
largest = r;
}
int temp;
if(largest != i)
{
temp = heapArray[i];
heapArray[i] = heapArray[largest];
heapArray[largest] = temp;
Max_Heapify(heapArray,largest);
}
return;
}
..................................................... .........................................................
int Parent(int i)
{
return (i/2);
}
int Left(int i)
{
return (2*i);
}
int Right(int i)
{
return ((2*i)+1);
}