测试用的IDE是牛客网:https://www.nowcoder.com/questionTerminal/508f66c6c93d4191ab25151066cb50ef
【1】快速排序
#include <vector>
#include <random>
#include <algorithm>
#include <iostream>
using namespace std;
template<typename T>
T partition(vector<T> &v, int l, int r){
// 随机化排序的中点,优化性能
default_random_engine e;
int rad = e()%(r - l) + l;
swap(v[l], v[rad]);
int p = l;
while(l < r){
while(r > l && v[r] >= v[p]){
r--;
}
while(l < r && v[l] <= v[p]){
l++;
}
if(v[r] < v[l]){
swap(v[l], v[r]);
}
}
swap(v[p], v[r]);
return r;
}
template<typename T>
void quick_sort(vector<T> &v, const int l, const int r)
{
if(l >= r){
return;
}
int p = partition(v, l, r);
quick_sort(v, l, p - 1);
quick_sort(v, p + 1, r);
}
template<typename T>
void my_sort(vector<T> &v){
quick_sort(v, 0, v.size() - 1);
for(int i = 0; i < v.size(); ++i){
cout << v[i] << " ";
}
cout << endl;
}
int main(){
int n;
while(cin >> n){
vector<int> v;
v.reserve(n);
for(int i = 0; i < n; ++i)
{
int tmp;
cin >> tmp;
v.push_back(tmp);
}
my_sort(v);
}
}
【2】堆排序
STL中有对堆操作的函数:https://blog.youkuaiyun.com/cillyb/article/details/52224330
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
template<typename T>
void heap_shiftUp(vector<T> &v, int begin, int position) // 这是一个大顶堆,上浮
{
if(position == begin)
return;
T value = v[position];
int parent = (position - 1)/2;
int node = position;
while(node > begin && value > v[parent]){
v[node] = v[parent];
node = parent;
parent = (node - 1)/2;
}
v[node] = value;
}
template<typename T>
int get_child(vector<T> &v, int end, int node)
{
int child1 = (node + 1)*2;
int child2 = child1 - 1;
int child;
if(child2 >= end){
return node;
}
else if(child1 >= end){
child = child2;
}
else child = (v[child1] > v[child2]) ? child1 : child2;
return child;
}
template<typename T>
void heap_shiftDown(vector<T> &v, int end, int position) // 这是一个大顶堆, 下沉
{
T value = v[position];
int node = position;
int child = get_child(v, end, node);
while(node < child && value < v[child]){
v[node] = v[child];
node = child;
child = get_child(v, end, node);
}
v[node] = value;
}
template<typename T>
void make_heap(vector<T> &v)
{
for(unsigned int i = 1; i < v.size(); ++i){
heap_shiftUp(v, 0, i);
}
}
template<typename T>
void heap_sort(vector<T> &v){
for(int i = v.size() - 1; i > 0; i--){
swap(v[i], v[0]);
heap_shiftDown(v, i, 0);
}
}
template<typename T>
void my_sort(vector<T> &v){
make_heap(v);
heap_sort(v);
for(int i = 0; i < v.size(); ++i){
cout << v[i] << " ";
}
cout << endl;
}
int main(){
int n;
while(cin >> n){
vector<int> v;
v.reserve(n);
for(int i = 0; i < n; ++i)
{
int tmp;
cin >> tmp;
v.push_back(tmp);
}
my_sort(v);
}
}