堆排序

codeblocks 17 通过

Code

// @ChenYe 2018/12/05
#include <iostream>
#define MAXSIZE 1000

using namespace std;
int len;    // 全局长度变量ing namespace std;
int Count = 0;  // 计数
void Swap(int a[], int i, int j)
{
	int temp;

	temp = a[i];
	a[i] = a[j];
	a[j] = temp;
}

void HeapAdjust(int a[], int s, int n)
{// 假设a[s+1...n]已经是堆,将a[s...m]调整为以a[s]为根的大根堆
    int temp = a[s];
    for(int i=s*2; i<=n; i=i*2) // 将s子树调整为大根堆
    {// i为s的左右孩子
        Count++;
        if(i<n && a[i]<a[i+1])  ++i;    // 将i指向较大的孩子
        // 找到合适的位置插入
        if(temp >= a[i])    break;
        a[s] = a[i];
        s=i;
    }// <end for>
    a[s] = temp;    // 插入
}

void HeapSort(int a[])
{
    int i;
    for(i=len/2; i>0; --i)  // 把无需序列a[1...len]创建大根堆
    {
        HeapAdjust(a,i,len);
    }

    for(i=len; i>1; --i)    // 排序
    {
        Swap(a,1,i);    // 交换a[1] a[i]
        HeapAdjust(a,1,i-1);  // 重新调整a[1...i-1]
    }
}

int main()
{
    int num[MAXSIZE];
    int n,i, key;
    // 输入
    for(n=1; n<MAXSIZE; n++)    // 从下表1开始!!
    {
        cin>>key;
        if(key==0)
            break;
        num[n] = key;
    }
    len = n-1;

    // 堆排序
    HeapSort(num);

    // output
    for(i=1; i<n; i++)
    {
        cout<<num[i]<<" ";
    }
    //cout<<"sum up to"<<Count<<endl;
    return 0;
}
/*
test data:
输入:
1 9 8 5 7 6 4 3 2 0
输出:
1 2 3 4 5 6 7 8 9


*/

附图

数据结构——堆排序

数据结构——堆排序 

要点

结点一定是堆中所有结点最大或者最小者,如果按照层序遍历的方式给结点从1开始编号,则结点之间满足如下关系

      ki>=k2i  &&  ki>=k2i+1    或     ki<=k2i && ki<=k2i+1     (1<=i<=n/2⌋)

下标i2i2i+1是双亲和子女关系。

那么把大顶堆和小顶堆用层序遍历存入数组,则一定满足上面的表达式。

堆排序算法

堆排序(Heap Sort)就是利用堆进行排序的算法,它的基本思想是:

将待排序的序列构造成一个大顶堆(或小顶堆)。

此时,整个序列的最大值就是堆顶的根结点。将它移走(就是将其与堆数组的末尾元素交换,此时末尾元素就是最大值)。

然后将剩余的n-1个序列重新构造成一个堆,这样就会得到n个元素中的此大值。

如此反复执行,便能得到一个有序序列了。

相关文章:

  • 2021-10-06
  • 2022-12-23
  • 2021-08-04
  • 2021-05-17
  • 2021-10-03
  • 2021-11-14
猜你喜欢
  • 2021-08-25
  • 2021-04-25
  • 2021-09-01
  • 2021-06-14
  • 2021-11-18
相关资源
相似解决方案