🌈个人主页:羽晨同学
💫个人格言:“成为自己未来的主人~”
昨天我们实现的堆的搭建,我们今天实现以下堆的排序,
堆的排序的最大的优点就是提高的效率,减小了时间复杂度,在这个里面我们有一个向上调整堆,时间复杂度是N,还有一个向下调整算法,时间复杂度是N*logN
下面是实现的代码:
#define _CRT_SECURE_NO_WARNINGS
#include"code.4.22.Heap.h"
void HPInit(HP* php)
{
assert(php);
php->a = NULL;
php->capacity = php->size = 0;
}
void HPInitArray(HP* php, HPDataType* a, int n)
{
assert(php);
php->a = (HPDataType*)malloc(sizeof(HPDataType) * n);
if (php->a == NULL)
{
perror("malloc fail");
return;
}
memcpy(php->a, a, sizeof(HPDataType) * n);
php->capacity = php->size = n;
//向上调整 建堆o(N*logN)
for (int i = 1; i < php->size; i++)
{
AdjustUp(php->a, i);
}
//向下调整,建堆o(N)
for (int i = (php->size - 1 - 1) / 2; i >= 0; i--)
{
AdjustDown(php->a, php->size, i);
}
}
void HPDestroy(HP* php)
{
assert(php);
free(php->a);
php->a = NULL;
php->capacity = php->size = 0;
}
void Swap(HPDataType* px, HPDataType* py)
{
HPDataType tmp = *px;
*px = *py;
*py = tmp;
}
void AdjustUp(HPDataType* a, int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (a[child] > a[parent])
{
Swap(&a[child], &a[parent]);
child = parent;
parent = (parent - 1) / 2;
}
else
{
break;
}
}
}
//插入后保证数据是堆
void HPPush(HP*php, HPDataType x)
{
assert(php);
if (php->capacity == php->size)
{
size_t newCapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
HPDataType* tmp = realloc(php->a, sizeof(HPDataType) * newCapacity);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
php->a = tmp;
php->capacity = newCapacity;
}
php->a[php->size] = x;
php->size++;
AdjustUp(php->a, php->size - 1);
}
HPDataType HPTop(HP* php)
{
assert(php);
return php->a[0];
}
void AdjustDown(HPDataType* a, int n, int parent)
{
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n && a[child] < a[child + 1])
{
child++;
}
if (a[child] > a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
//删除堆顶的数据
void HPPop(HP* php)
{
assert(php);
assert(php->size > 0);
Swap(&php->a[0], &php->a[php->size - 1]);
php->size--;
AdjustDown(php->a, php->size, 0);
}
bool HPEmpty(HP* php)
{
assert(php);
return php->size == 0;
}
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
typedef int HPDataType;
typedef struct Heap
{
HPDataType* a;
int size;
int capacity;
}HP;
void HPInit(HP* php);
void HPInitArray(HP* php, HPDataType* a, int n);
void HPDestroy(HP* php);
//插入后保证数据是堆
void HPPush(HP* php,HPDataType x);
//删除堆顶的数据
void HPPop(HP* php);
bool HPEmpty(HP* php);
void AdjustUp(HPDataType* a, int child);
void AdjustDown(HPDataType* a, int n, int parent);
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include"code.4.22.Heap.h"
void HeapSort(int* a, int n)
{
//数组a直接建堆
for (int i = (n - 1 - 1) / 2; i >= 0; i--)
{
AdjustDown(a, n, i);
}
int end = n - 1;
while (end > 0)
{
Swap(&a[0], &a[end]);
AdjustDown(a, end, 0);
end--;
}
}
int main()
{
int a[] = { 3,6,1,5,8,9,2,7,4,0 };
HeapSort(a, sizeof(a) / sizeof(a[0]));
return 0;
}