网上堆排序用到的数组,很多都是从1开始进行排序。我做了改进,可以从0开始。希望能够帮助大家,如果有错误,非常感激能够指出。
#include <stdio.h>
void print_arr3(int arr[], int count)
{
int i;
printf("\n_____ current list:\n");
for(i=0; i<count; i++)
{
printf("%d ",arr[i]);
}
}
void AdjustTree4(int arr[], int index, int size)
{
int child;
int value, temp;
child = index * 2 + 1;
value = arr[index];
while (child < size)
{
if ((child + 1) < size && arr[child] < arr[child + 1])
child = child + 1;
if (arr[child] > value)
{
arr[index] = arr[child];
index = child;
child = index * 2 + 1;
}
else
child = size;
}
arr[index] = value;
}
void HeapSort4(int arr[], int size)
{
if (size <= 0)
return;
int index = (size-1)/2;
for (; index>=0; index--)
{
AdjustTree4(arr, index, size);
}
for (index = size - 1; index>=0; index--)
{
int temp;
temp = arr[0];
arr[0] = arr[index];
arr[index] = temp;
AdjustTree4(arr, 0, index);
}
}
int main(int argc, char *argv[])
{
int n;
// int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 34};
int arr[] = {1, 2, 3, 4, 28, 15, 78, 72, 56, 7, 8, 34, 32, 23, 21, 56, 65, 34, 21, 11, 3, 4, 6, 23};
n = sizeof(arr) / sizeof(arr[0]);
HeapSort4(arr, n);
print_arr3(arr, n);
return 0;
}