C++常用排序算法


一、算法简介

1、sort //对容器内元素进行排序

2、random_shuffle //洗牌 指定范围内的元素随机调整次序

3、merge //容器元素合并,并存储到另一容器中

4、reverse //反转指定范围的元素

二、sort

1、函数原型

sort(iterator beg,iterator end,_Pred); //_Pred谓词

2、示例

代码如下(示例):

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
void MyPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int>v;
	v.push_back(30);
	v.push_back(50);
	v.push_back(20);
	v.push_back(40);
	v.push_back(10);
	//用sort做升序处理
	sort(v.begin(), v.end());
	for_each(v.begin(), v.end(), MyPrint);
	cout << endl;
	sort(v.begin(), v.end(), greater<int>());
	cout << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

三、random_shuffle

1、函数原型

random_shuffle(iterator beg,iterator end); //指定范围内的元素随机调整次序

2、示例

代码如下(示例):

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
void MyPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int>v;
	v.push_back(30);
	v.push_back(50);
	v.push_back(20);
	v.push_back(40);
	v.push_back(10);
	//用sort做升序处理
	sort(v.begin(), v.end());
	for_each(v.begin(), v.end(), MyPrint);
	cout << endl;
	sort(v.begin(), v.end(), greater<int>());
	cout << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

四、merge

1、功能描述

两个容器元素合并,并存在另外一个容器里

2、函数原型

merge(iterator beg1,iterator end1,iterator beg2,iterator end2,iterator dest); //容器元素合并,dest目标容器开始迭代器

注意:两个容器必须是有序的

3、示例

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int>v;
	vector<int>v2;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
		v2.push_back(i + 1);
	}
	//目标容器
	vector<int>vTarget;
	//提前给目标容器分配空间
	vTarget.resize(v.size() + v2.size());
	merge(v.begin(), v.end(), v2.begin(), v2.end(), vTarget);
	for_each(vTarget.begin(), vTarget.end(),myPrint);
}
int main()
{
	test01();
	system("pause");
	return 0;
}

五、reverse

1、函数原型

reverse(iterator beg,iterator end); //反转指定范围的元素

2、示例

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myPrint(int val)
{
	cout << val << " ";
}
void test01()
{
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	cout << "反转前:" << endl;
	for_each(v.begin(), v.end(), myPrint);
	cout << endl;
	reverse(v.begin(), v.end());
	cout << "反转后:" << endl;
	for_each(v.begin(), v.end(), myPrint);

}
int main()
{
	test01();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值