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;
}
相关推荐
Hanniel6 分钟前
Python 元类(下):进阶与实战建议
开发语言·python
会编程的土豆10 分钟前
Go interface 底层的 itab 到底是什么
开发语言·后端·golang
千纸鹤の脉搏15 分钟前
多线程的初步了解---进程与线程
java·开发语言·学习·线程
秋田君36 分钟前
Qt 5.12.8 下载与安装教程(附网盘资源)
开发语言·qt
故事和你9140 分钟前
洛谷-【动态规划2】线性状态动态规划4
开发语言·数据结构·c++·算法·动态规划·图论
不吃土豆的马铃薯43 分钟前
Socket 网络编程实战教程
linux·服务器·开发语言·网络·c++·算法
零号全栈寒江独钓1 小时前
c++跨平台实现日志重定向
linux·c++·windows
小成202303202651 小时前
从C到C++
开发语言·c++
折哥的程序人生 · 物流技术专研1 小时前
《Java 100 天进阶之路》第39篇:Java泛型方法的定义和使用
java·开发语言·后端·面试·求职招聘
天天进步20151 小时前
Tunnelto 源码解析 #1:从 tunnelto --port 8000 看内网穿透的完整链路
开发语言