堆排序(最小堆)--【算法导论】

时间:2021-02-13 16:24:34

堆排序的思想在堆排序(最大堆)已做说明,故不再赘述;

总之,思想就是首先进行建堆,由于这是最小堆,故而必须保证父节点都小于孩子节点,若不满足条件,则进行调节;

最后进行堆排序,不断将最小的提取出来,并对剩下的进行调节,使之满足最小堆

故而将最大堆中的判断父节点与孩子大小部分改变即可:

    if (left <= length && A[largest] > A[left])  //左孩子比父节点小
{
largest = left;
}

if (right <= length && A[largest] > A[right]) //右孩子最小
{
largest = right;
}

这样,就将最大堆改为最小堆了...

完整代码:

#include <iostream>
#include <cstdlib>

using namespace std;

void MinHeapIfy(int A[], int length, int i) //维护
{
int left = i * 2 + 1; //节点i的左孩子
int right = left + 1; //节点i的右孩子节点
int largest = i; //默认父节点

if (left <= length && A[largest] > A[left]) //左孩子比父节点小
{
largest = left;
}

if (right <= length && A[largest] > A[right]) //右孩子最小
{
largest = right;
}

if (i != largest) //最小值不是父节点
{
int temp = A[largest]; //exchange
A[largest] = A[i];
A[i] = temp;

MinHeapIfy(A, length, largest); //继续维护
}
}

void BuildMinHeap(int A[], int length) //建堆
{
for (int i = (length - 1) / 2; i >= 0; i--)
{
MinHeapIfy(A, length, i);
}
}

void HeapSort(int A[], int length) //堆排
{
int temp;

BuildMinHeap(A, length); //建堆

cout<<"建堆情况:"; //
for(int i = 0; i <= length; i++)
cout<<A[i]<<" ";
cout<<endl;

for(int i = length; i >= 1;) //最后一个肯定是最小的
{
temp = A[i]; //交换堆的第一个元素和堆的最后一个元素
A[i] = A[0];
A[0] = temp;
i--; //堆的大小减一
MinHeapIfy(A, i, 0); //调堆
}
}

int main()
{
int A[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
/*int* A = new int[1000];
A[0] = 0;
for(int i = 1; i < 1000; i++)
A[i] = rand()%10000 + 1;*/

int length = sizeof(A) / sizeof(int); //
//int length = 1000;
HeapSort(A, length - 1);

cout<<"排序结果:";
for(int i = 0; i < length; i++) //cout
cout<<A[i]<<" ";
cout<<endl;

return 0;
}

堆排序(最小堆)--【算法导论】

 

o(∩_∩)o