C++之常用的排序算法
sort
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<functional>
void Myptint(int val)
{cout << val << " ";
}void test()
{vector<int> v;v.push_back(10);v.push_back(20);v.push_back(50);v.push_back(30);v.push_back(40);//利用sort进行排序(默认是升序)sort(v.begin(), v.end());for_each(v.begin(),v.end(), Myptint);cout << endl;//改变为降序sort(v.begin(), v.end(), greater<int>());for_each(v.begin(), v.end(), Myptint);cout << endl;
}int main()
{test();system("pause");return 0;
}
random_shuffle
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<ctime>
void Myptint(int val)
{cout << val << " ";
}void test()
{//随机种子srand((unsigned int)time(NULL));vector<int> v;for (int i = 0; i < 10; i++){v.push_back(i);}random_shuffle(v.begin(), v.end());for_each(v.begin(), v.end(), Myptint);cout << endl;
}int main()
{test();system("pause");return 0;
}
merge
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>void Myptint(int val)
{cout << val << " ";
}void test()
{vector<int> v;vector<int>v2;for (int i = 0; i < 10; i++){v.push_back(i);v2.push_back(i+1);}//目标容器vector<int>Target;//提前给目标容器分配空间Target.resize(v.size()+v2.size());merge(v.begin(), v.end(), v2.begin(), v2.end(), Target.begin());for_each(Target.begin(), Target.end(), Myptint);cout << endl;
}int main()
{test();system("pause");return 0;
}
reverse
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>void Myptint(int val)
{cout << val << " ";
}void test()
{vector<int> v;for (int i = 0; i < 10; i++){v.push_back(i);}//反转前cout << "反转前" << endl;for_each(v.begin(), v.end(), Myptint);cout << endl;cout << "反转后" << endl;reverse(v.begin(), v.end());for_each(v.begin(), v.end(), Myptint);cout << endl;
}int main()
{test();system("pause");return 0;
}