我试图按升序对10个元素的数组实施堆排序。 我以下步骤 -堆排序C - 不正确的输出
heap_sort(ARR,size_array):
build_max_heap(arr)
for(parent=size_array to 1):
swap(arr[1],arr[parent])
size_array = size_array - 1;
max_heapify(arr,1,size);
但我的输出是完全搞砸了。 我不知道我要去哪里错了。
这是我的输入 -
20 15 10 1 15 9 2 6 7 9
我build_max_heap输出 -
20 15 10 7 15 9 2 6 1 9
我的有序数组是一样的build_max_heap输出 -
20 15 10 7 15 9 2 6 1 9
我在做什么错?
这里是我的代码:
void max_heapify(int *arr,int i,int size)
{
//i is the index of parent node. 2i is left child, 2i+1 is right
int left = (2*i)+1;
int right = (2*i)+2;
int max;
int temp;
//check which node is the max, parent or one of its children. store max idx.
if ((left<=size)&&(arr[left]>arr[i]))
max = left;
else
max = i;
if ((right<=size)&&(arr[right]>arr[max]))
max = right;
//swap parent with max.
if(max!=i)
{
temp = arr[max];
arr[max]=arr[i];
arr[i]=temp;
max_heapify(arr,max,size);
}
}
void build_max_heap(int *arr,int size)
{
for(int i = size/2; i>=0; i--)
{
max_heapify(arr,i,size);
}
}
void heap_sort(int *arr, int size)
{
int temp;
build_max_heap(arr,size);
int i = size;
while(size>0)
{
//swap
temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
//reduce size
size = size -1;
//heapify
max_heapify(arr,0,size);
}
}
逐行扫描代码,看看它是否按预期工作。 –