完成此功能需要四个函数来实现
第一个是交换函数:交换数组中两个数的位置;
第二个是heapinsert:建立大根堆的函数
第三个是heapify函数:假设取走第一个大根堆的数,然后接着建立大根堆
第四个是排序函数:先用heapinsert来建立这个数组的大根堆,然后将第一个数与最后一个数交换,然后在除最后一个数之外的数组进行堆化。
void swap(int* nums, int i, int j) {
int temp = *(nums + i);
*(nums + i) = *(nums + j);
*(nums + j) = temp;
}
void heapinsert(int* nums, int index) {
while (nums[index] > nums[(index - 1) / 2]) {
swap(nums, index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
void heapify(int* nums, int index, int heapSize) {
int left = index * 2 + 1;
int largest = 0;
while (left < heapSize) {
largest = left + 1 < heapSize && nums[left] < nums[left + 1] ? left + 1 : left;
largest = nums[largest] > nums[index] ? largest : index;
if (largest == index) break;
swap(nums, largest, index);
left = index * 2 + 1;
}
}
void heapsort(int* nums, int numsSize) {
if (nums == NULL || numsSize < 2) return;
int heapSize=numsSize-1;
for ( int i = 0; i < numsSize; i++) {
heapinsert(nums,i);
}
while (heapSize >= 0) {
swap(nums, 0, heapSize);
heapSize--;
heapify(nums, 0, heapSize);
}
}