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;
}
相关推荐
天若有情6736 分钟前
从构造函数到Vue3响应式:C++中“常量转特殊类型”的隐藏大招
开发语言·c++
计算机学姐17 分钟前
基于Python的B站数据分析及可视化系统【2026最新】
开发语言·vue.js·python·信息可视化·数据挖掘·数据分析·推荐算法
沐知全栈开发20 分钟前
《XHR.readyState详解及在JavaScript中的应用》
开发语言
qq_4335545424 分钟前
C++ 进阶动态规划(小明的背包3)
开发语言·c++·动态规划
YouEmbedded24 分钟前
解码继承——代码复用与层次化设计
开发语言·c++·继承
有点。28 分钟前
C++ ⼀级 2023 年 12 ⽉
c++
这是个栗子31 分钟前
【JS知识点总结】JavaScript 中的精确取整:Math.floor、Math.ceil 与 Math.round
开发语言·javascript·ecmascript
FMRbpm37 分钟前
顺序表实现队列
数据结构·c++·算法·新手入门
飞天狗11139 分钟前
G. Mukhammadali and the Smooth Array
数据结构·c++·算法
红石程序员1 小时前
Python环境管理
开发语言·python