C++之常用的排序算法

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;
}
相关推荐
微露清风19 分钟前
系统性学习C++-第五讲-内存管理
java·c++·学习
qiuiuiu41323 分钟前
正点原子RK3568学习日志-编译第一个驱动程序helloworld
linux·c语言·开发语言·单片机
molong9311 小时前
Kotlin 内联函数、高阶函数、扩展函数
android·开发语言·kotlin
盼哥PyAI实验室1 小时前
踏上编程征程,与 Python 共舞
开发语言·python
阿无,1 小时前
Java设计模式之工厂模式
java·开发语言·设计模式
星夜钢琴手1 小时前
推荐的 Visual Studio 2026 Insider C++ 程序项目属性配置
c++·visual studio
weixin_307779132 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
ss2732 小时前
手写MyBatis第104弹:SqlSession从工厂构建到执行器选择的深度剖析
java·开发语言·后端·mybatis
kyle~2 小时前
Qt---setAttribute设置控件或窗口的内部属性
服务器·前端·c++·qt
周杰伦_Jay3 小时前
【Java集合体系】全面解析:架构、原理与实战选型
java·开发语言·数据结构·链表·架构