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;
}
相关推荐
码界筑梦坊3 分钟前
240-基于Python的医疗疾病数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·echarts
2301_8035545213 分钟前
C++ 锁类型大全详解
开发语言·c++
wuwu_q20 分钟前
用通俗易懂方式,详细讲讲 Kotlin Flow 中的 map 操作符
android·开发语言·kotlin
曼巴UE524 分钟前
UE5 C++ Slate 画曲线
开发语言·c++·ue5
ue星空27 分钟前
UE5C++UKismetMathLibrary源代码
c++·ue5
向葭奔赴♡30 分钟前
Spring IOC/DI 与 MVC 从入门到实战
java·开发语言
minji...34 分钟前
C++ 面向对象三大特性之一---多态
开发语言·c++
散峰而望40 分钟前
基本魔法语言函数(一)(C语言)
c语言·开发语言·编辑器·github
2401_841495641 小时前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
lucky_syq1 小时前
Scala与Spark算子:大数据处理的黄金搭档
开发语言·spark·scala