浅析C/C++中sort函数的用法

本文转自:

浅析C/C++中sort函数的用法

sort函数对数组、容器以及结构体的排序(for sort)

        做项目的时候,排序是一种经常要用到的操作。如果每次都自己写个冒泡之类的O(n^2)排序,不但程序容易超时,而且浪费宝贵的时间,还很有可能写错。STL里面有个sort函数,可以直接对数组排序,复杂度为n*log2(n)。

sort是STL中提供的算法,头文件为#include<algorithm>以及using namespace std; 函数原型如下:

template <class RandomAccessIterator>
 void sort ( RandomAccessIterator first, RandomAccessIterator last );

template <class RandomAccessIterator, class Compare>
 void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

使用第一个版本是对[first,last)进行升序排序,默认操作符为"<",第二个版本使用comp函数进行排序控制,comp包含两个在[first,last)中对应的值,如果使用"<"则为升序排序,如果使用">"则为降序排序,分别对int、float、char以及结构体排序例子如下:

#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;

struct product{
	char name[16];
	float price;
};

int array_int[5]={4,1,2,5,3};
char array_char[5]={'a','c','b','e','d'};
double array_double[5]={1.2,2.3,5.2,4.6,3.5};

//结构比较函数(按照结构中的浮点数值进行排序)
bool compare_struct_float(const product &a,const product &b){
	return a.price<b.price;
}
//结构比较函数(按照结构中的字符串进行排序)
bool compare_struct_str(const product &a,const product &b){
	return string(a.name)<string(b.name);
}
//打印函数
void print_int(const int* a,int length){
	printf("升序排序后的int数组:\n");
	for(int i=0; i<length-1; i++)
		printf("%d ",a[i]);
	printf("%d\n",a[length-1]);
}
void print_char(const char* a,int length){
	printf("升序排序后的char数组:\n");
	for(int i=0; i<length-1; i++)
		printf("%c ",a[i]);
	printf("%c\n",a[length-1]);
}
void print_double(const double* a,int length){
	printf("升序排序后的dobule数组:\n");
	for(int i=0; i<length-1; i++)
		printf("%.2f ",a[i]);
	printf("%.2f\n",a[length-1]);
}
void print_struct_array(struct product *array, int length) 
{ 
  for(int i=0; i<length; i++) 
    printf("[ name: %s \t price: $%.2f ]\n", array[i].name, array[i].price); 
  puts("--");
}
void main()
{
	struct product structs[] = {{"mp3 player", 299.0f}, {"plasma tv", 2200.0f}, 
               {"notebook", 1300.0f}, {"smartphone", 499.99f}, 
               {"dvd player", 150.0f}, {"matches", 0.2f }};
	//整数排序
	sort(array_int,array_int+5);
	print_int(array_int,5);
	//字符排序
	sort(array_char,array_char+5);
	print_char(array_char,5);
	//浮点排序
	sort(array_double,array_double+5);
	print_double(array_double,5);
	//结构中浮点排序
	int len = sizeof(structs)/sizeof(struct product);
	sort(structs,structs+len,compare_struct_float);
	printf("按结构中float升序排序后的struct数组:\n");
	print_struct_array(structs, len); 
	//结构中字符串排序
	sort(structs,structs+len,compare_struct_str);
	printf("按结构中字符串升序排序后的struct数组:\n");
	print_struct_array(structs, len); 
}

sort函数的用法

做ACM题的时候,排序是一种经常要用到的操作。如果每次都自己写个冒泡之类的O(n^2)排序,不但程序容易超时,而且浪费宝贵的比赛时间,还很有可能写错。STL里面有个sort函数,可以直接对数组排序,复杂度为n*log2(n)。使用这个函数,需要包含头文件。

    这个函数可以传两个参数或三个参数。第一个参数是要排序的区间首地址,第二个参数是区间尾地址的下一地址。也就是说,排序的区间是[a,b)。简单来说,有一个数组int a[100],要对从a[0]到a[99]的元素进行排序,只要写sort(a,a+100)就行了,默认的排序方式是升序。

    拿我出的“AC的策略”这题来说,需要对数组t的第0到len-1的元素排序,就写sort(t,t+len);
    对向量v排序也差不多,sort(v.begin(),v.end());
    排序的数据类型不局限于整数,只要是定义了小于运算的类型都可以,比如字符串类string。
    如果是没有定义小于运算的数据类型,或者想改变排序的顺序,就要用到第三参数——比较函数。比较函数是一个自己定义的函数,返回值是bool型,它规定了什么样的关系才是“小于”。想把刚才的整数数组按降序排列,可以先定义一个比较函数cmp

bool cmp(int a,int b)
{
  return a>b;
}


   排序的时候就写sort(a,a+100,cmp);

   假设自己定义了一个结构体node

struct node{
  int a;
  int b;
  double c;
}


   有一个node类型的数组node arr[100],想对它进行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b还相同,就按c降序排列。就可以写这样一个比较函数:

以下是代码片段:

bool cmp(node x,node y)
{
   if(x.a!=y.a) return x.a
if(x.b!=y.b) return x.b>y.b;
   return return x.c>y.c;
}

排序时写sort(arr,a+100,cmp);

qsort(s[0],n,sizeof(s[0]),cmp);
int cmp(const void *a,const void *b)
{
  return *(int *)a-*(int *)b;
}

一、对int类型数组排序 

int num[100]; 
Sample: 
int cmp ( const void *a , const void *b ) 
{ 
return *(int *)a - *(int *)b; 
} 
qsort(num,100,sizeof(num[0]),cmp); 

二、对char类型数组排序(同int类型) 

char word[100]; 
Sample: 
int cmp( const void *a , const void *b ) 
{ 
return *(char *)a - *(int *)b; 
} 
qsort(word,100,sizeof(word[0]),cmp); 

三、对double类型数组排序(特别要注意) 

double in[100]; 
int cmp( const void *a , const void *b ) 
{ 
return *(double *)a > *(double *)b ? 1 : -1; 
} 
qsort(in,100,sizeof(in[0]),cmp);

四、对结构体一级排序 

struct In 
{ 
double data; 
int other; 
}s[100] 
//按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种,参考上面的例子写 
int cmp( const void *a ,const void *b) 
{ 
return ((In *)a)->data - ((In *)b)->data ; 
} 
qsort(s,100,sizeof(s[0]),cmp); 

五、对结构体

struct In 
{ 
int x; 
int y; 
}s[100]; 
//按照x从小到大排序,当x相等时按照y从大到小排序 
int cmp( const void *a , const void *b ) 
{ 
struct In *c = (In *)a; 
struct In *d = (In *)b; 
if(c->x != d->x) return c->x - d->x; 
else return d->y - c->y; 
} 
qsort(s,100,sizeof(s[0]),cmp); 

六、对字符串进行排序 

struct In 
{ 
int data; 
char str[100]; 
}s[100]; 
//按照结构体中字符串str的字典顺序排序 
int cmp ( const void *a , const void *b ) 
{ 
return strcmp( ((In *)a)->str , ((In *)b)->str ); 
} 
qsort(s,100,sizeof(s[0]),cmp); 

七、计算几何中求凸包的cmp 

int cmp(const void *a,const void *b) //重点cmp函数,把除了1点外的所有点,旋转角度排序 
{ 
struct point *c=(point *)a; 
struct point *d=(point *)b; 
if( calc(*c,*d,p[1]) < 0) return 1; 
else if( !calc(*c,*d,p[1]) && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y)) //如果在一条直线上,则把远的放在前面 
return 1; 
else return -1; 
}

首先,sort函数可以对数组和结构体进行排序,还是用实例说话吧!一句话,都在代码里!

[cpp]  view plain copy
  1. #include<iostream>  
  2. #include<string>  
  3. #include<algorithm>  
  4. #include<vector>  
  5. using namespace std;  
  6. bool cmp(int i,int j)  
  7. {  
  8.     return (i>j);  
  9. }  
  10. int main()  
  11. {  
  12.     int num[]={5,2,9,7,1,6,4,8,3};  
  13.     vector<int>data(num,num+9);  
  14.     vector<int>::iterator it;  
  15.     int i;  
  16.     cout<<"原始数据:"<<endl;  
  17.     for(i=0;i<9;i++)  
  18.     {  
  19.         cout<<num[i]<<" ";  
  20.     }  
  21.     cout<<endl;  
  22.     cout<<"对前四个数排序:"<<endl;  
  23.     sort(num,num+4);// 2 5 7 9 1 6 4 8 3  
  24.     for(i=0;i<9;i++)  
  25.     {  
  26.         cout<<num[i]<<" ";  
  27.     }  
  28.     cout<<endl;  
  29.     cout<<"按从大到小排列输出:"<<endl;  
  30.     sort(data.begin(),data.end(),cmp);  
  31.     for(it=data.begin();it!=data.end();it++)  
  32.     {  
  33.         cout<<*it<<" ";  
  34.     }  
  35.     cout<<endl;  
  36.     return 0;  
  37.   
  38. }  

有时,我们进行的排序所依据的因素有多个,比如我们在对acm竞赛人员的成绩进行排名时,往往先依据他们的解答出来的题目数,如果题目数相同了,我们就会依据他们所用的时间来进行排名,这时往往会涉及结构体的二级排序,下面介绍结构体的一级和二级排序!

[cpp]  view plain copy
  1. #include<iostream>  
  2. #include<algorithm>  
  3. using namespace std;  
  4. struct node  
  5. {  
  6.     int num;  
  7.     int age;  
  8. }example[5];  
  9. bool cmp(node a,node b)  
  10. {  
  11.     return a.num>b.num;  
  12. }  
  13. bool cmp2(node a,node b)  
  14. {  
  15.     if(a.num!=b.num)  
  16.         return a.num>b.num;  
  17.     else  
  18.         return a.age<b.age;  
  19. }  
  20. int main()  
  21. {  
  22.     int i;  
  23.     for(i=0;i<5;i++)  
  24.     {  
  25.         cin>>example[i].num>>example[i].age;  
  26.     }  
  27.     sort(example,example+5,cmp);  
  28.     cout<<"---after sorting by cmp---"<<endl;  
  29.     for(i=0;i<5;i++)  
  30.     {  
  31.         cout<<example[i].num<<" "<<example[i].age<<endl;  
  32.     }  
  33.     sort(example,example+5,cmp2);  
  34.     cout<<"---after sorting by cmp2---"<<endl;  
  35.     for(i=0;i<5;i++)  
  36.     {  
  37.         cout<<example[i].num<<" "<<example[i].age<<endl;  
  38.     }  
  39.     return 0;  
  40. }  
  41.       





  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值