Sorting Algorithm - Heap Sort

Heapsort (English: Heapsort) refers to a sorting algorithm designed using the data structure of the heap. The heap is a structure that approximates a complete binary tree, and at the same time satisfies the nature of the heap: that is, the key value or index of a child node is always smaller (or larger) than its parent node.

In the data structure of the heap, the maximum value in the heap is always located at the root node (if the heap is used in the priority queue, the minimum value in the heap is located at the root node). The following operations are defined in the heap:
Max Heapify: Adjust the end child nodes of the heap so that the child nodes are always smaller than the parent node
Build Max Heap: Reorder all the data in the
heap Sorting (HeapSort): remove the bit at the root node of the first data, and do the recursive operation of the maximum heap adjustment

—The above is from Baidu Encyclopedia

Among them, the big top heap and the small top heap correspond to the ascending and descending order of the algorithm.
This code takes the ascending order of the big top heap as an example:

Program function :
void swap(int *a,int *b)
void heapify(int *a,int len,int i)//Maintenance of the heap, change the value of the parent node i to the maximum number of the heap.
void heapsort(int *a,int len)//heap sort entry

Basic knowledge : (for specific knowledge, please refer to data structure - heap, binary tree)
each parent node with subscript i: (i-1)/2;
each left child node with subscript i: 2 i+1
each Right child node with subscript i: 2
i+2
insert image description here

Full code :

#include<stdio.h>

void swap(int *a,int *b)
{
    
    
	int temp;
	temp=*a;
	*a=*b;
	*b=temp;
}
void heapify(int *a,int len,int i)//堆的维护,把父节点i的数值变成此堆最大的数。
{
    
    
	int largest=i,lson=i*2+1,rson=i*2+2;
	if(lson<len && a[largest]<a[lson])largest=lson;
	if(rson<len && a[largest]<a[rson])largest=rson;
	if(largest!=i)
	{
    
    
		swap(&a[i],&a[largest]);
		heapify(a,len,largest);
	}
}
/*
基本知识:
每个下标为i的父节点:(i-1)/2;
每个下标为i的左孩子节点:2*i+1
每个下标为i的右孩子节点:2*i+2
*/

void heapsort(int *a,int len)//堆排序入口
{
    
    
	int i;
	for(i=(len/2-1);i>=0;i--)//从最后一个父节点开始维护,建堆
	{
    
    
		heapify(a,len,i);
	}

	for(i=len-1;i>0;i--)//把最后的数和堆顶值交换,然后再进行堆的维护
	{
    
    
		swap(&a[0],&a[i]);//把堆顶最大的数和堆尾的数交换
		heapify(a,i,0);//对堆顶进行维护,最大的数始终要在堆顶
	}
}

int main()
{
    
    
	int i;
	int a[]={
    
    3,5,1,-7,4,9,-6,8,10,4};
	int len=(int)sizeof(a)/sizeof(int);
	heapsort(a,len);
	for(i=0;i<len;i++)printf("%3d",a[i]);
	printf("\n");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44627822/article/details/121474193