[Data structure] Downward adjustment algorithm of heap sort

Algorithm analysis

To understand the downward adjustment algorithm, we must first grasp the definition of the heap in the data structure (not the heap in memory).
1. Concept: Heap data structure is an array object, which can be regarded as a complete binary tree structure.
2. Heap classification: maximum heap: the value of each parent node is greater than the child node. Minimal heap: the value of each parent node is less than the child node

The function of the downward adjustment algorithm is to turn any heap into the smallest heap or the largest heap by sorting the algorithm from top to bottom.

Steps: (Take the minimum heap as an example)
1. Select a smaller value min from the left and right children of the root node
2. Compare the current data that needs to be adjusted with the smaller value min

①, greater than min: exchange with min, continue to execute step 1 from the position after the exchange;
②, less than or equal to min: end

Code

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

//向下调整算法---以最小堆为例
void Shift_down(int *arr, int n, int curpos) //n-数组大小   curpos-需要调整的位置
{
    
    
	//左孩子
	int child = 2 * curpos + 1;
	while (child < n)
	{
    
    
		if (child + 1 < n&&arr[child + 1] < arr[child])
			child++;
		//向下比较
		if (arr[child] < arr[curpos])
		{
    
    
			int tmp = arr[child];
			arr[child] = arr[curpos];
			arr[curpos] = tmp;

			//继续向下比较
			curpos = child;
			child = 2 * curpos + 1;
		}
		else
			break;
	}

}


void test()
{
    
    
	int arr[] = {
    
     10,5,3,8,7,6 };
	Shift_down(arr, sizeof(arr) / sizeof(arr[0]), 0);
}

int main()
{
    
    
	test();
	return 0;
}

Debug result

Test case: array [10, 5, 3, 8, 7, 6]

Forecast output results: [3, 5, 6, 8, 7, 10]

Actual output result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43962381/article/details/112147016
Recommended