C++ 中的sort排序用法

C++ 中的sort排序用法

C中的qsort()采用的是快排算法,C++的sort()则是改进的快排算法。两者的时间复杂度都是n*(logn),但是实际应用中,sort()一般要快些,建议使用sort()。
STL中就自带了排序函数sort对给定区间所有元素进行排序 要使用此函数只需用
#include sort即可使用,语法描述为:
sort(begin,end),表示一个范围,用法示例:

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[10]={1,5,2,4,5,7,9,6,3,4},i;
	sort(a,a+10);
	for(i=0;i<10;i++)
	    cout<<a[i]<<endl;
	return 0;
}

输出显示:

1
2
3
4
4
5
5
6
7
9

--------------------------------
Process exited after 0.4222 seconds with return value 0
请按任意键继续. . .


输出结果将是把数组a按升序排序;
如果想将其按照降序排序,即需自己定义一个比较函数:
用法示例:

bool cmp(int a,int b)
{
	return a<b;   //升序排列,如果换成a>b,则为降序排列 
 } 
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
	return a>b;   //降序排列,如果换成a<b,则为升序排列 
 } 
int main()
{
	int a[10]={1,5,2,4,5,7,9,6,3,4},i;
	sort(a,a+10,cmp);
	for(i=0;i<10;i++)
	    cout<<a[i]<<endl;
	return 0;
}

输出结果:

9
7
6
5
5
4
4
3
2
1

--------------------------------
Process exited after 2.921 seconds with return value 0
请按任意键继续. . .

对浮点型数据也是一样,用法示例:

#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
bool cmp(double a,double b)
{
	return a>b;   //降序排列,如果换成a<b,则为升序排列 
 } 
int main()
{
	double a[10]={1,5,2,4,5,7,9,6,3,4};
	int i;
	sort(a,a+10,cmp);
	cout<<fixed<<showpoint<<setprecision(2);
	for(i=0;i<10;i++)
	    cout<<a[i]<<endl;
	return 0;
}

输出结果:


9.00
7.00
6.00
5.00
5.00
4.00
4.00
3.00
2.00
1.00

--------------------------------
Process exited after 0.2294 seconds with return value 0
请按任意键继续. . .


还可以按照结构体排序:

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct link
{
    int a,b;
};
bool cmp(link x,link y)
{
    if(x.a==y.a)
        return x.b>y.b;
    return x.a>y.a;
}
int main()
{
    link x[4];
    for(int i=0;i<4;i++)
        cin>>x[i].a>>x[i].b;
    sort(x,x+4,cmp);
    for(int i=0;i<4;i++)
        cout<<x[i].a<<' '<<x[i].b<<endl;
    return 0;
 }

输出结果:

9.00
7.00
6.00
5.00
5.00
4.00
4.00
3.00
2.00
1.00

--------------------------------
Process exited after 0.2294 seconds with return value 0
请按任意键继续. . .

发布了6 篇原创文章 · 获赞 9 · 访问量 145

猜你喜欢

转载自blog.csdn.net/weixin_45882303/article/details/104181430