堆结构就是用数组实现的完全二叉树结构
优先级队列结构,就是堆结构
大根堆
完全二叉树中如果每棵子树的最大值都在顶部就是大根堆 时间复杂度O(log N)
int heapInsert(int nums[], int index)
{
while(nums[index] > nums[(index - 1) / 2])
{
swap(nums, index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
int swap(int nums[], int i, int j)
{
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
去除堆中最大值,其余仍为大根堆结构
时间复杂度O(log N)
int heapify(int nums[], int index, int heapSize)
{
int left = index * 2 + 1;
while(left < heapSize)
{
if(left + 1 < heapSize && nums[left + 1] > nums[left])
{
int largest = left + 1;
}else largest = left;
if(nums[largest] > nums[index])
{
largest = largest;
}else largest = index;
if(largest = index){break;}
swap(nums, largest, index);
index = largest;
left = index * 2 + 1;
}
}
int swap(int nums[], int i, int j)
{
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
1、堆排序
时间复杂度O(N * log N),额外空间复杂度O(1)
#include <stdio.h>
int main()
{
int i;
int nums[] = {3,4,3,6,2};
int numsSize = sizeof(nums) / sizeof(int);
heapSort(nums, numsSize);
for(i = 0; i < numsSize; i++)
{
printf("%d", nums[i]);
}
}
int heapSort(int nums[], int numsSize)
{
int i;
int heapSize = numsSize;
if(nums == NULL || numsSize < 2) {return;}
for(i = numsSize - 1; i >= 0; i--)
{
heapify(nums, i, heapSize);
}
swap(nums, 0, --heapSize);
while(heapSize > 0)
{
heapify(nums, 0, heapSize);
swap(nums, 0, --heapSize);
}
}
int heapInsert(int nums[], int index)
{
while(nums[index] > nums[(index - 1) / 2])
{
swap(nums, index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
int heapify(int nums[], int index, int heapSize)
{
int largest;
int left = index * 2 + 1;
while(left < heapSize)
{
if(left + 1 < heapSize && nums[left + 1] > nums[left])
{
largest = left + 1;
}else largest = left;
if(nums[largest] > nums[index])
{
largest = largest;
}else largest = index;
if(largest = index){break;}
swap(nums, largest, index);
index = largest;
left = index * 2 + 1;
}
}
int swap(int nums[], int i, int j)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
|