Heap sorting C language implementation

Insert picture description here

Algorithm features:
1. Unstable sorting
2. Can only be used for sequential structure, not for chain structure
3. The number of comparisons required for initial pile building is large, so the number of records is small and should not be used. In the worst case, the time complexity of heap sort is O(nlogn), which is an advantage compared to O(n*n) of quick sort. It is more efficient when there are more records.

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
void HeapAdjust(int *a,int s,int length){
    
    
    int t=a[s];
    for(int i=2*s;i<=length;i=i*2){
    
    
            if(i+1<=length&&a[i]<a[i+1]) i=i+1;
            if(t>a[i]) break;
            a[s]=a[i];s=i;
    }
    a[s]=t;

}
void CreatHead(int *a,int x){
    
    
for(int i=x/2;i>0;i--)
    HeapAdjust(a,i,x);
}

void HeapSort(int *a,int length){
    
    
    CreatHead(a,length);
    for(int i=length;i>1;i--){
    
    
        int x=a[1];
        a[1]=a[i];
        a[i]=x;
        HeapAdjust(a,1,i-1);
    }

}

int main()
{
    
    
    int a[9]={
    
    0,49,38,65,97,76,13,27,49};
    HeapSort(a,8);
    for(int i=1;i<=8;i++)
        cout<<a[i]<<" ";
    //cout << "Hello world!" << endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/changbaishannefu/article/details/111596428