What is heap sorting, using C language to simulate heap sorting

What is heap sort

Heap sort is a sorting algorithm based on the heap data structure. A heap is a complete binary tree, which can be divided into a maximum heap and a minimum heap. The parent node of the largest heap is always greater than or equal to the left and right child nodes, and the parent node of the smallest heap is always less than or equal to the left and right child nodes. In heap sorting, the array to be sorted is first constructed into a maximum heap or a minimum heap, and then the top element of the heap is exchanged with the last element in turn, and then the heap is readjusted so that the remaining elements meet the characteristics of the heap again. This process will be like "sinking", sometimes called "heaping", until all elements are sorted. The time complexity is O(nlogn).


The following is the code to implement heap sorting in C language

#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

// 调整堆
void heap_adjust(int arr[], int i, int n)
{
    int j, tmp;
    tmp = arr[i];
    j = 2 * i + 1;
    while (j < n) {
        if (j + 1 < n && arr[j + 1] > arr[j]) {
            j++;
        }
        if (arr[j] <= tmp) {
            break;
        }
        arr[i] = arr[j];
        i = j;
        j = 2 * i + 1;
    }
    arr[i] = tmp;
}

// 堆排序函数
void heap_sort(int arr[], int len)
{
    int i;
    // 构造初始堆
    for (i = len / 2 - 1; i >

Guess you like

Origin blog.csdn.net/q6115759/article/details/130506519