【源代码】C++数据结构算法(十七)排序——堆排序

日常说明:有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
这里写图片描述
HeapSort.cpp

#include "HeapSort.h"


HeapSort::HeapSort()
{
    return;
}
void HeapSort::Swap(int &a, int &b)//交换位置
{
    int temp = a;
    a = b;
    b = temp;
}


void HeapSort::HeapAdjust(int arr[], int root, int length)
{
    int lchild = root * 2 + 1;
    if (lchild!=NULL&&lchild < length)  
    {
        int temp = lchild;
        int rchild = lchild + 1;  
        if (rchild < length) 
        {
            if (arr[rchild] > arr[temp])//找出左右子结点中的最大值  
            {
                temp = rchild;
            }
        }
        if (arr[root] < arr[temp])
        {
            Swap(arr[root], arr[temp]);
            HeapAdjust(arr, temp, length);//从此次最大子节点的那个位置开始递归建堆  
        }
    }
}

void HeapSort::Heap_sort(int arr[], int len)
{
    for (int i = len / 2; i >= 0; --i)//从最后一个非叶子节点的父结点开始建堆  
    {
        HeapAdjust(arr, i, len);
    }

    for (int j = len - 1; j > 0; --j) 
    {
        Swap(arr[0], arr[j]);//交换首尾元素,将最大值交换到数组的最后位置保存  
        HeapAdjust(arr, 0, j);//去除最后位置的元素重新建堆
    }

}

int main()
{
    HeapSort heapsort;
    int length;
    cout << "请输入数组的长度:";
    cin >> length;
    cout << endl;
    int *arr = new int[length];
    cout << "请输入无序的数组元素:";
    for (int i = 0; i < length; i++)
    {
        cin >> arr[i];
    }
    heapsort.Heap_sort(arr, length);
    cout << "堆排序后的结果:";
    for (int i = 0; i <length; ++i)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    cout << endl;
    return 0;
}

HeapSort.h

#pragma once
#include <iostream>  
using namespace std;

class HeapSort
{
public:
    void HeapAdjust(int arr[],int root,int length);
    void Swap(int &a,int &b);
    void Heap_sort(int arr[], int length);
    HeapSort();
};

我看留言说需要更多的注释,因为这些算法是比较基础简单的算法。如果先把算法基本思想弄懂了,再看代码会比较容易看懂,否则看什么代码都是一头雾水的。最好是自己写一遍,遇到问题后再参考别人的处理手段,网络上很多代码,变量名,函数名,以及语法不规范的也有很多,需要对比和思考。

猜你喜欢

转载自blog.csdn.net/Handoking/article/details/80446701