关于c++中的sort有些时候不然C语言的qsort这件事
众所周知,c++中有stl库中自带的sort函数,进一步说,还有stable_sort来增加稳定性
但是,别忘了,在c库<stdlib.h>库中,还有一个按位排序的qsort算法,类似于
qsort(目标数组名,排序元素个数,排序元素单个的大小,排序函数(入参均为const void*,返回值为int类型,不能像c++这样随意))
但是——它都标明了q(quick)了,和c++sort相比会如何呢?是逊色很多,还是名副其实?
实验如下:(int为例)
#include<iostream>
#include<random>
#include<algorithm>
#include<time.h>
#define arrlen(ar) (sizeof(ar)/sizeof((ar)[0]))
#define arrmove(a,b) memcpy(a,b,sizeof(b))
#include<memory.h>
using namespace std;
#define qsort_cmper(name,type)\
int name(const void *a,const void *b)\
{if(*(type*)a<*(type*)b)return -1;\
if(*(type*)b<*(type*)a)return 1;\
return 0;}//关于qsortcmp的通用写法
qsort_cmper(ccmp,int)
#define N 10000000//10^7级
random_device ram;
uniform_int_distribution<int>kg(-1000000,1000000);
//为了避免rand这个伪随机数垃圾重复出数字
int a[N],s[N];
int main(){
for(int i=0;i<arrlen(a);++i)a[i]=kg(ram);
arrmove(s,a);
clock_t e=clock(),b;
sort(s,s+N);
b=clock();
printf("%lld\n",b-e);
arrmove(s,a);
e=clock();
stable_sort(s,s+N);
b=clock();
printf("%lld\n",b-e);
arrmove(s,a);
e=clock();
qsort(s,N,4,ccmp);
b=clock();
printf("%lld\n",b-e);
}
结果是这样的
Sort:3586
Stable_sort:3725
Qsort:3120
但在10^5的条件下:
Sort:20
Stable_sort:30
Qsort:25
所以说,Qsort的绝对优势实在数据量很多(如10^6的状态下),但Sort更方便。
你看这个Stable_sort就是逊也~
qsort还有一个sort不可达到的方式,那就是对于静态多维数组(二维数组)排序。
学过c++的都知道,数组作为c++的特色,不能直接用=赋值,传达参数也得用指向数组的指针,贼麻烦,而sort不仅用类安全加大了麻烦,而且赋值操作还直接拒中括号静态数组鱼门外
而qsort就不同了,void*传递避免类型问题(“类型不安全”),交换按位交换,省去等号烦恼,而传递的比较参数稍加类型转换就能在数组上操作,只需要写好单个元素的大小和比较函数就比c++不知好上太多(虽然c++有vector)
就拿c风格字符串来说吧:
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
char a[21][100]={"I love your mother fucker","The car I just bought","I fuck your mum","Fuck You!","The car is still new!","Fuck you mother","Your Mother Fucker the car I just bought"};
int main(){
qsort(a,7,100,(int (*)(const void*,const void*))strcmp);//没错,强行拉上strcmp
for(int i=0;i<7;i++)cout<<a[i]<<'\n';
}
So~在数据过大时排序与排序c风格二维数组时,sort不如qsort
如果喜欢的话,就关注小金鱼我吧~
CSDN账号正在注册,名字叫“呼唤伙伴的小金鱼”