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;
}
相关推荐
iCxhust2 小时前
c# U盘映像生成工具
开发语言·单片机·c#
yangzhi_emo3 小时前
ES6笔记2
开发语言·前端·javascript
emplace_back4 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk4 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶4 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl4 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
夜月yeyue4 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
收破烂的小熊猫~4 小时前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
nananaij5 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm