常用排序算法
算法简介
sort
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
void test() {
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(20);
v.push_back(60);
v.push_back(50);
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
sort(v.begin(), v.end(), greater<int>());
for_each(v.begin(), v.end(), myPrint);
}
int main() {
test();
return 0;
}
random_shuffle
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<ctime>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
void test() {
srand((unsigned int)time(NULL));
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(20);
v.push_back(60);
v.push_back(50);
sort(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
cout << endl;
random_shuffle(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
}
int main() {
test();
return 0;
}
merge
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
void test() {
vector<int> v;
for (int i = 0; i < 5; ++i) {
v.push_back(i);
}
vector<int> v2;
for (int i = 5; i < 10; ++i) {
v.push_back(i);
}
vector<int> v3;
v3.resize(v.size() + v2.size());
merge(v.begin(), v.end(), v2.begin(), v2.end(), v3.begin());
for_each(v3.begin(), v3.end(), myPrint);
}
int main() {
test();
return 0;
}
reverse
功能描述
函数原型
示例
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
void myPrint(int val) {
cout << val << " ";
}
void test() {
vector<int> v;
for (int i = 0; i < 5; ++i) {
v.push_back(i);
}
for_each(v.begin(), v.end(), myPrint);
cout << endl;
reverse(v.begin(), v.end());
for_each(v.begin(), v.end(), myPrint);
}
int main() {
test();
return 0;
}