C ++中的排序 --sort排序
用法
先使用 algorithm 头文件
bool cmp(int a,int b)
{
return a<b; //排序后是升序排列
return a>b;// 排序后是降序排列
}
在函数中 用sort( a+? , a+?,cmp)来实现
如果没有cmp 就是默认升序;
对数组/字符数组排序
sort(a,a+?) 这里从数组开始到数组结束这里是按数组的长度来使用
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[5]={3,1,4,2,5};
sort(a,a+5);
cout <<endl;
for(int i=0;i<5;i++)
cout <<a[i]<<endl;
return 0;
}
对其中的部分一段一段的排序
例一
两段排序
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
if(a!=b) return a<b;
}
int main()
{
int a[5]={1,5,3,4,2};
// cin >>a;
sort(a,a+3,cmp); //丛下标为0开始 排序三个
sort(a+3,a+5,cmp); //丛下标为3 开始排序5-3=2 个
for(int i=0;i<5;i++)
{
cout <<a[i];
}
return 0;
}
输出结果为 1 3 5 2 4
例二
一段排序
#include<iostream>
#include<algorithm>
using namespace std;
/char s[10];
int a[10];
int main()
{
for(int i=0;i<5;i++)
cin >>a[i];
sort(a+1,a+5); //对多少个排序
//**从下标为1 ** 排序5-1=4个
for(int i=0;i<10 ;i++)
cout <<a[i];
return 0;
}
对数组字符串排序
#include<iostream>
#include<algorithm>
using namespace std;
string a[5];
int main()
{
for(int i=0;i<5;i++)
cin >>a[i];
sort(a,a+5);
cout <<endl;
for(int i=0;i<5;i++)
cout <<a[i]<<endl;
return 0;
}
对个数未知情况之下
sort(a.begin(),a.end(),)
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string a="I LOVE YOU";
sort(a.begin(),a.end()); //在stirng 情况下可能用
cout <<a<<endl; //输出: EILOOUVY(注意空格);
return 0;
}