AcWing 838 堆排序

AcWing 838 堆排序


文章目录


🤖 作者简介: w20,自律才有自由 ⭐⭐⭐

输入:

5 3
4 5 1 3 2

输出:

1 2 3

//AcWing 838 堆排序
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
typedef long long ll;
const int N= 10010;
int n; 
int ph[N],hp[N],h[N],size;
//ph[k]表示表示第k个插入的点在堆中的位置,hp[k]表示k是第几个插入到堆中的 
//h[k]存储堆中的值,h[1]是堆顶,2x是左儿子,2x+1是右儿子 
void heap_swap(int a,int b)
{
	swap(ph[hp[a]],ph[hp[b]]);
	swap(hp[a],hp[b]);
	swap(h[a],h[b]);
}
void down(int u)
{
	int t=u;
	if(u*2 <=n &&h[t]>h[u*2])t=2*u;
	if(u*2+1 <=n &&h[t]>h[u*2+1])t=2*u+1;
	if(u!=t)
	{
		heap_swap(u,t);
		down(t);
	}
}
void up(int u)
{
	while(u/2 && h[u]<h[u/2])
	{
		heap_swap(u,u/2);
		u>>=1;
	}
}
void create_heap()//构建堆,构建成最小堆 
{
	for(int i=n/2;i;i--)
	{
		down(i);
	}
}
void delete_heap()//删除堆顶,重构堆 
{
	heap_swap(1,size--);
	down(1);
}

int main()
{
	int m;
	cin>>n>>m;
	size=n; 
	for(int i=1;i<=n;i++)
	{
		cin>>h[i];
	}
	create_heap();
	while(m--)
	{
		cout<<h[1]<<' ';
		delete_heap();
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
堆排序是一种高效的排序算法,它利用了堆的数据结构来实现排序。堆是一个完全二叉树,具有以下性质:对于任意节点 i,其父节点的值小于等于子节点的值。 堆排序的基本思路如下: 1. 构建最大堆:将待排序的数组看作是一个完全二叉树,从最后一个非叶子节点开始,依次向上调整每个节点,使得以该节点为根的子树满足最大堆的性质。 2. 将堆顶元素与最后一个元素交换:将最大堆的堆顶元素(即数组的第一个元素)与数组最后一个元素交换位置,此时最大元素就位于数组的最后。 3. 调整堆:将剩余元素重新调整为最大堆。 4. 重复步骤 2 和步骤 3,直到所有元素都排序完成。 以下是堆排序C++ 代码实现: ```cpp #include <iostream> using namespace std; // 调整以 root 为根的子树为最大堆 void heapify(int arr[], int n, int root) { int largest = root; // 假设根节点最大 int left = 2 * root + 1; // 左子节点索引 int right = 2 * root + 2; // 右子节点索引 // 若左子节点大于根节点,更新最大值索引 if (left < n && arr[left] > arr[largest]) { largest = left; } // 若右子节点大于最大值节点,更新最大值索引 if (right < n && arr[right] > arr[largest]) { largest = right; } // 若最大值不是根节点,交换根节点和最大值 if (largest != root) { swap(arr[root], arr[largest]); // 递归调整交换后的子树 heapify(arr, n, largest); } } void heapSort(int arr[], int n) { // 构建最大堆 for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } // 逐步取出最大值,调整堆 for (int i = n - 1; i > 0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } } int main() { int arr[] = {4, 10, 3, 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); heapSort(arr, n); cout << "Sorted array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; } ``` 以上就是堆排序的基本思路和实现方法。堆排序的时间复杂度为 O(nlogn),其中 n 为数组的长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值