#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<stdbool.h>
void Swap(int *nums, int a, int b)
{
int midNum = nums[a];
nums[a] = nums[b];
nums[b] = midNum;
}
void Heapify(int *nums, int numsSize,int idx)
{
int left = 2 * idx + 1;
int right = 2 * idx + 2;
while (left < numsSize ) {
int childMax = right < numsSize && nums[left] > nums[right] ? left : right;
int bothMax = nums[childMax] > nums[idx] ? childMax : idx;
if (bothMax == idx) {
break;
}
Swap(nums, idx, childMax);
idx = childMax;
left = 2 * idx + 1;
right = 2 * idx + 2;
}
}
void HeapInsert(int *nums, int numsIdx)
{
int index = numsIdx;
while (nums[index] > nums[index / 2]) {
if (nums[index] > nums[index / 2]) {
Swap(nums, index / 2, index);
}
index = index / 2;
}
}
int main()
{
int nums[] = { 3, 2, 1, 5, 6, 4 };
for (int i = 0; i < 6; i++) {
HeapInsert(nums, i);
}
for (int i = 0; i < 6; i++) {
printf("%d ", nums[i]);
}
printf("\n");
int numsSize = 6;
for (int i = 0; i < 6; i++) {
printf("%d ", nums[0]);
numsSize--;
Swap(nums, 0, numsSize);
Heapify(nums, numsSize, 0);
}
getchar();
return 0;
}