当前位置:网站首页>Binary tree (II) -- code implementation of heap
Binary tree (II) -- code implementation of heap
2022-07-05 22:24:00 【Thousands of people live in spring trees in the rain】
Heap uses array to realize its physical structure , utilize leftchild=2*parent+1 as well as rightchild=2*parent+2 Access parent and child nodes .
The basic structure of the heap :
typedef int HPDataType;
typedef struct Heap {
HPDataType* a;// The dynamic array
size_t size;// Data volume
size_t capacity;// Capacity
}HP;
Initialization function of heap :
void HeapInit(HP* php)
{
assert(php);
php->a = NULL;
php->size = php->capacity = 0;
}Heap zeroing function
void HeapDesTroy(HP* php)
{
assert(php);
free(php->a);
php->a = NULL;// Don't neglect this step
php->size = php->capacity = 0;
}When adding new elements to the heap , should :
① Keep large root pile ( Or a little pile of roots ) The original nature of is inconvenient , That is, after inserting new elements, it is still a large root heap ( Or a little pile of roots ).
② Try not to destroy the integrity of the original tree structure .
③ Adopt tail insertion , There is no need to move data in large quantities , To improve efficiency .
Functions that insert new elements into the heap (AdjustUp Adjust the function up ):
void AdjustUp(HPDataType* a,size_t child)
{
// Calculation formula of parent-child relationship ( about leftchild and rightchild All set up )
size_t parent = (child - 1) / 2;
// May continue to rise
// Here is a small pile , If you need a lot , Only adjust if Just use the symbol in
while (child>0)
{
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
// Update the relationship
child = parent;
parent = (child - 1) / 2;
// Be careful child=0 when ,parent=0, Will fall into a dead cycle .
// Don't use it size_t,parent Never less than 0
//-1/2==0
}
// We should also consider the situation of stopping in the middle
else
{
break;
}
}
}
// After inserting new data , Keep a big pile 、 The nature of small root pile
void HeapPush(HP* php, HPDataType x)
{
assert(php);
// Space is not enough , Expand first
if (php->capacity == php->size)
{
size_t newCapacity = php->capacity * 2 + 1;
HPDataType* tmp = realloc(php->a, sizeof(HPDataType) * newCapacity);
if (tmp == NULL)
{
printf("realloc failed.\n");
exit(-1);
}
php->a = tmp;
php->capacity = newCapacity;
}
// Insert data into the heap —— Adjust the algorithm up
// First step : First put the new data in the physical structure ( The order sheet / Array ) Tail of
php->a[php->size] = x;
++php->size;
// The second step : Adjust up
AdjustUp(php->a, php->size - 1);
}Delete the function of the root
void AdjustDown(HPDataType* a,size_t size,size_t root)
{
size_t parent = root;
size_t child = parent * 2 + 1;
while (child < size)
{
// First step : Choose the younger of the left and right children
if (child + 1 < size && a[child + 1] < a[child])
{
child++;
}
// If the child is smaller than the father, exchange , And continue to adjust down
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
// Delete heap top data ( Little heap - Delete the minimum data at the top of the heap / A lot - Delete the maximum data at the top of the heap )
// Keep small piles / The nature of the pile
// If you directly move the remaining data forward , There's a problem :① Destroy the structure ② The time complexity is O(N), inconvenient
// Better solution : The first data is exchanged with the last data -> Don't erase the data , direct size-- that will do -> Downward adjustments
void HeapPop(HP* php)
{
assert(php);
assert(php->size > 0);
// First step : The root exchanges with the last data
Swap(&php->a[0], &php->a[php->size-1]);
// The second step : Delete data
--php->size;
// The third step : Downward adjustments
// Time complexity :O(logN)
AdjustDown(php->a,php->size,0);
}Heap sort function
// The steps of heap sorting are relatively simple , namely :
// Put all the unordered elements in the array into a new heap , In turn pop Out , That is, the ordered element column
// Heap sort —— Ascending
void HeapSort(HPDataType* a, int size)
{
// First step : Build a heap ( Little heap )
HP hp;
HeapInit(&hp);
// The second step : Put the unordered data in the array into the heap
// The third step : Because the small heap can pop up data from small to large in turn , So you can put it into the array in turn
for (int i = 0; i < size; ++i)
{
HeapPush(&hp, a[i]);
}
size_t j = 0;
while (!HeapEmpty(&hp))
{
a[j] = HeapTop(&hp);
j++;
HeapPop(&hp);
}
HeapDesTroy(&hp);
}Complete code ( Including test cases )
Heap.h
#pragma once
#include<stdlib.h>
#include<assert.h>
#include<stdio.h>
#include<stdbool.h>
typedef int HPDataType;
typedef struct Heap {
HPDataType* a;// The dynamic array
size_t size;// Data volume
size_t capacity;// Capacity
}HP;
void Swap(HPDataType* pa, HPDataType* pb);
void HeapInit(HP* php);
void HeapDesTroy(HP* php);
void HeapPush(HP* php, HPDataType x);
void HeapPop(HP* php);
void HeapPrint(HP* php);
HPDataType HeapTop(HP* php);
size_t HeapSize(HP* php);
bool HeapEmpty(HP* php);Heap.c
#include"Heap.h"
void HeapInit(HP* php)
{
assert(php);
php->a = NULL;
php->size = php->capacity = 0;
}
void HeapDesTroy(HP* php)
{
assert(php);
free(php->a);
php->a = NULL;// Don't neglect this step
php->size = php->capacity = 0;
}
void Swap(HPDataType* pa, HPDataType* pb)
{
HPDataType tmp = *pa;
*pa = *pb;
*pb = tmp;
}
// The idea of algorithmic logic is binary tree , The physical operation is the data in the array
void AdjustUp(HPDataType* a,size_t child)
{
// Calculation formula of parent-child relationship ( about leftchild and rightchild All set up )
size_t parent = (child - 1) / 2;
// May continue to rise
// Here is a small pile , If you need a lot , Only adjust if Just use the symbol in
while (child>0)
{
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
// Update the relationship
child = parent;
parent = (child - 1) / 2;
// Be careful child=0 when ,parent=0, Will fall into a dead cycle .
// Don't use it size_t,parent Never less than 0
//-1/2==0
}
// We should also consider the situation of stopping in the middle
else
{
break;
}
}
}
// After inserting new data , Keep a big pile 、 The nature of small root pile
void HeapPush(HP* php, HPDataType x)
{
assert(php);
// Space is not enough , Expand first
if (php->capacity == php->size)
{
size_t newCapacity = php->capacity * 2 + 1;
HPDataType* tmp = realloc(php->a, sizeof(HPDataType) * newCapacity);
if (tmp == NULL)
{
printf("realloc failed.\n");
exit(-1);
}
php->a = tmp;
php->capacity = newCapacity;
}
// Insert data into the heap —— Adjust the algorithm up
// First step : First put the new data in the physical structure ( The order sheet / Array ) Tail of
php->a[php->size] = x;
++php->size;
// The second step : Adjust up
AdjustUp(php->a, php->size - 1);
}
void HeapPrint(HP* php)
{
assert(php);
for (size_t i = 0; i < php->size; i++)
{
printf("%d ",php->a[i]);
}
printf("\n");
}
void AdjustDown(HPDataType* a,size_t size,size_t root)
{
size_t parent = root;
size_t child = parent * 2 + 1;
while (child < size)
{
// First step : Choose the younger of the left and right children
if (child + 1 < size && a[child + 1] < a[child])
{
child++;
}
// If the child is smaller than the father, exchange , And continue to adjust down
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
// Delete heap top data ( Little heap - Delete the minimum data at the top of the heap / A lot - Delete the maximum data at the top of the heap )
// Keep small piles / The nature of the pile
// If you directly move the remaining data forward , There's a problem :① Destroy the structure ② The time complexity is O(N), inconvenient
// Better solution : The first data is exchanged with the last data -> Don't erase the data , direct size-- that will do -> Downward adjustments
void HeapPop(HP* php)
{
assert(php);
assert(php->size > 0);
// First step : The root exchanges with the last data
Swap(&php->a[0], &php->a[php->size-1]);
// The second step : Delete data
--php->size;
// The third step : Downward adjustments
// Time complexity :O(logN)
AdjustDown(php->a,php->size,0);
}
HPDataType HeapTop(HP* php)
{
assert(php);
assert(php->size > 0);
return php->a[0];
}
size_t HeapSize(HP* php)
{
assert(php);
return php->size;
}
bool HeapEmpty(HP* php)
{
assert(php);
return php->size == 0;
}main.c
#include"Heap.h"
void TestHeap()
{
HP hp;
HeapInit(&hp);
HeapPush(&hp, 1);
HeapPush(&hp, 5);
HeapPush(&hp, 0);
HeapPush(&hp, 8);
HeapPush(&hp, 3);
HeapPush(&hp, 9);
HeapPrint(&hp);
HeapPop(&hp);
HeapPrint(&hp);
HeapDesTroy(&hp);
}
// The steps of heap sorting are relatively simple , namely :
// Put all the unordered elements in the array into a new heap , In turn pop Out , That is, the ordered element column
// Heap sort —— Ascending
void HeapSort(HPDataType* a, int size)
{
// First step : Build a heap ( Little heap )
HP hp;
HeapInit(&hp);
// The second step : Put the unordered data in the array into the heap
// The third step : Because the small heap can pop up data from small to large in turn , So you can put it into the array in turn
for (int i = 0; i < size; ++i)
{
HeapPush(&hp, a[i]);
}
size_t j = 0;
while (!HeapEmpty(&hp))
{
a[j] = HeapTop(&hp);
j++;
HeapPop(&hp);
}
HeapDesTroy(&hp);
}
int main()
{
TestHeap();
HPDataType a[] = { 4,2,7,8,5,1,0,6 };
HeapSort(a, sizeof(a) / sizeof(HPDataType));
for (size_t i = 0; i <= 7; i++)
printf("%d ", a[i]);
return 0;
}边栏推荐
- 1.3 years of work experience, double non naked resignation agency face-to-face experience [already employed]
- Server optimization of performance tuning methodology
- Overview of database recovery
- 90后测试员:“入职阿里,这一次,我决定不在跳槽了”
- Metaverse ape received $3.5 million in seed round financing from negentropy capital
- 2022-07-05: given an array, you want to query the maximum value in any range at any time. If it is only established according to the initial array and has not been modified in the future, the RMQ meth
- Implementing Lmax disruptor queue from scratch (IV) principle analysis of multithreaded producer multiproducersequencer
- 点到直线的距离直线的交点及夹角
- MySQL disconnection reports an error MySQL ldb_ exceptions. OperationalError 4031, The client was disconnected by the server
- Overriding equals() & hashCode() in sub classes … considering super fields
猜你喜欢

极狐公司官方澄清声明

Technology cloud report won the special contribution award for the 10th anniversary of 2013-2022 of the "cloud Ding Award" of the global cloud computing conference

boundary IoU 的计算方式

50. Pow(x, n). O(logN) Sol
![[error record] file search strategy in groovy project (src/main/groovy/script.groovy needs to be used in the main function | groovy script directly uses the relative path of code)](/img/b6/b2036444255b7cd42b34eaed74c5ed.jpg)
[error record] file search strategy in groovy project (src/main/groovy/script.groovy needs to be used in the main function | groovy script directly uses the relative path of code)

Calculation method of boundary IOU
![[error record] groovy function parameter dynamic type error (guess: groovy.lang.missingmethodexception: no signature of method)](/img/3e/34b45cd14f0302bb381efd244bc68f.jpg)
[error record] groovy function parameter dynamic type error (guess: groovy.lang.missingmethodexception: no signature of method)

Opencv judgment points are inside and outside the polygon

A substring with a length of three and different characters in the leetcode simple question

Summary of concurrency control
随机推荐
The new content of the text component can be added through the tag_ Config set foreground and background colors
Cobaltstrike builds an intranet tunnel
Advantages and disadvantages of the "Chris Richardson microservice series" microservice architecture
New 3D particle function in QT 6.3
Concurrency control of performance tuning methodology
微服務鏈路風險分析
What changes has Web3 brought to the Internet?
Oracle advanced query
a-tree 树的全部展开和收起
C language knowledge points link
Win11缺少dll文件怎么办?Win11系统找不到dll文件修复方法
A trip to Suzhou during the Dragon Boat Festival holiday
2022-07-05:给定一个数组,想随时查询任何范围上的最大值。 如果只是根据初始数组建立、并且以后没有修改, 那么RMQ方法比线段树方法好实现,时间复杂度O(N*logN),额外空间复杂度O(N*
點到直線的距離直線的交點及夾角
Technology cloud report won the special contribution award for the 10th anniversary of 2013-2022 of the "cloud Ding Award" of the global cloud computing conference
Assign the output of a command to a variable [repeat] - assigning the output of a command to a variable [duplicate]
Draw a red lantern with MATLAB
1.3 years of work experience, double non naked resignation agency face-to-face experience [already employed]
科技云报道荣膺全球云计算大会“云鼎奖”2013-2022十周年特别贡献奖
CA certificate trampled pit