qsort与sort效率用法比较

来源:互联网 发布:炉石传说mac版2017 编辑:程序博客网 时间:2024/05/16 11:55

qsort与sort效率用法比较

很多枚举题目都需要用先排序再二分查找,虽然考的知识点主要是枚举的剪枝,但是二分查找和排序有时候也会成为时间的瓶颈。所以,在这种分秒必争的题目中,选择一个好的排序和二分查找算法函数来调用无以会节省一点点时间。

bsearch有现成的库函数,(注意这个拼写)调用格式为
find=(point_type*) bsearch((const void*) key,p,n,sizeof(point_type),compare);
而自己实现二分查找比较慢,且容易写错,耗费时间编程,而STL的binary_search()又伴随着容器,所以二分查找肯定使用bsearch()。

那么对于qsort与sort,建议用qsort(),因为qsort()比较快,而sort()对应了一个算法模板,属于C++风格的,更慢一些,qsort调用格式为
qsort(p,n,sizeof(point_type),compare);

其中compare与bsearch中一样,格式为
int _type_compare(const void* e1,const void* e2)
{
return ((const _type*) e1)->num-((const _type*) e2)->num;
}

下面的代码比较了qsort和sort的效率,通过合理的宏定义可以开启不同测试模式

某一次测试的耗时为:


sort对int类型数据排序 2.576s
qsort对int类型数据排序 0.8418s


sort对结构类型数据排序 2.585s
qsort对结构类型数据排序 0.9964s


2.5-3倍的时间差距,差距还是很明显的,至于自己实现的二分查找或者STL的binary_search与bsearch效率差别可能更大。所以尽量用qsort+bsearch来实现。

#define QSORT#define SORT#define INT#define _TYPE#define MAX_LEN 10000000#include<stdio.h>#include<algorithm>#include<stdlib.h>using namespace std;struct _type{    int num;};_type* a;int *b;#ifdef QSORTint _type_compare(const void* e1,const void* e2){    return ((const _type*) e1)->num-((const _type*) e2)->num;}int int_compare(const void* e1,const void* e2){    return ((const int*) e1-(const int*) e2);}#endif#ifdef SORTbool _type_compare(_type e1,_type e2){    return e1.num<e2.num;}bool int_compare(int e1,int e2){    return e1<e2; }#endifint main(){    a=new _type[MAX_LEN];    b=new int[MAX_LEN];    for (int i=0;i<MAX_LEN;i++)        a[i].num=(i*i*i)%123;    for (int i=0;i<MAX_LEN;i++)        b[i]=(i*i*i)%123;     #ifdef QSORT    #ifdef INT        qsort(b,MAX_LEN,sizeof(int),int_compare);    #endif    #ifdef _TYPE        qsort(a,MAX_LEN,sizeof(_type),_type_compare);    #endif    #endif    #ifdef SORT    #ifdef INT        sort(b,b+MAX_LEN,int_compare);    #endif    #ifdef _TYPE        sort(a,a+MAX_LEN,_type_compare);    #endif    #endif    return 0;}
0 0