洛谷 P1177:【模板】排序 ← 堆排序实现
【题目来源】https://www.luogu.com.cn/problem/P1177https://www.acwing.com/problem/content/789/【题目描述】将读入的 N 个数从小到大排序后输出。【输入格式】第一行为一个正整数 N。第二行包含 N 个空格隔开的正整数 ai为你需要进行排序的数。【输出格式】将给定的 N 个数从小到大输出数之间空格隔开行末换行且无空格。【输入样例】54 2 4 5 1【输出样例】1 2 4 4 5【说明/提示】对于 20% 的数据有 1≤N≤10^3对于 100% 的数据有 1≤N≤10^51≤ai≤10^9。【算法分析】● 在 C 中int 类型通常能表示的数值范围是从 -2,147,483,648 ~ 2,147,483,647也即 -2^31 ~ 2^31-1小于 2.15×10^9。简单起见若整数大于 2×10^9就选择使用 long long 型。详见https://blog.csdn.net/hnjzsyjyj/article/details/132240042● 在 C 中若输入数据个数大于 10^5 时推荐使用 scanf 而不是 cin 输入数据。这是因为 scanf 通常比 cin 更快。详见https://blog.csdn.net/hnjzsyjyj/article/details/145618674● 算法时间复杂度与问题规模之间的关系详见https://blog.csdn.net/hnjzsyjyj/article/details/119816240● 问题规模达到 10^5 时可选的排序算法本题问题规模达到 10^5所以不能选择平均时间复杂度为 O(n^2) 的直接插入排序、折半插入排序、希尔排序、冒泡排序、简单选择排序只能选择平均时间复杂度为 O(nlogn) 的快速排序、堆排序、归并排序因为 O(n^2) 的时间复杂度支持的问题规模≤5000 的时间复杂度支持的问题规模≤10^6。本题选择“归并排序”实现。● sort() 函数的常见用法https://blog.csdn.net/hnjzsyjyj/article/details/130524018● 本题归并排序实现https://blog.csdn.net/hnjzsyjyj/article/details/145679752● 本题基数排序实现https://blog.csdn.net/hnjzsyjyj/article/details/153932655【算法代码堆排序】#include bits/stdc.h using namespace std; priority_queueint,vectorint,greaterint G; int main() { int n,x; cinn; while(n--) { cinx; G.push(x); } while(!G.empty()) { coutG.top() ; G.pop(); } return 0; }【算法代码二sort() 函数】利用 sort() 函数可以简单地实现排序。#include bits/stdc.h using namespace std; const int maxn1e55; int a[maxn]; int n; int main() { scanf(%d,n); for(int i1; in; i) { scanf(%d,a[i]); } sort(a1,a1n); for(int i1; in; i) { if(i!n) printf(%d ,a[i]); else printf(%d\n,a[i]); } return 0; } /* in: 5 4 2 4 5 1 out: 1 2 4 4 5 */【参考文献】https://blog.csdn.net/hnjzsyjyj/article/details/153932655https://blog.csdn.net/hnjzsyjyj/article/details/145679752https://blog.csdn.net/hnjzsyjyj/article/details/127841703