跳到正文

个人记录

堆排序

ycx303约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年8月7日
更新
2026年8月7日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <iostream>
#include <cmath>
using namespace std;
int a[100005];
void heapinsert(int pos)
{
	int t = (pos - 1) / 2;
	while (pos > 0 && a[pos] > a[t])
	{
		swap(a[pos], a[t]);
		pos = t;
		t = (pos - 1) / 2;
	}
}
void heapify(int pos, int r)
{
	int t = pos * 2 + 1;
	while (t < r)
	{
		int best = (t + 1 < r && a[t + 1] > a[t]) ? t + 1 : t;
		best = a[best] > a[pos] ? best : pos;
		if (best == pos) break;
		swap(a[best], a[pos]);
		pos = best;
		t = pos * 2 + 1;
	}
}
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i ++)
	{
		cin >> a[i];
		heapinsert(i);
	}
	int p = n;
	while (p > 1)
	{
		swap(a[0], a[p - 1]);
		p --;
		heapify(0, p);
	}
	for (int i = 0; i < n; i ++)
	{
		cout << a[i] << " "; 
	}
	cout << endl;
	return 0;
}
原文