1. 程式人生 > >qsort/sort函式之cmp

qsort/sort函式之cmp

C語言

void qsort(   待排序陣列首地址 ,   陣列中待排序元素數量 ,   各元素的佔用空間大小   ,  cmp(const void*,const void*)  );

標頭檔案: #include<stdlib.h>

C++

void sort(   待排序陣列首地址  ,  陣列首地址+陣列長度  , cmp  );

標頭檔案: #include<algorithm>

一般型別

1.qsort

cmp函式原理(以int型別為例):

bool cmp(const void *a,const void *b )

{
    return *(int *)a-*(int *b);    //降序排列
   //等同於 return *(int *)a>*(int *b);
}

當函式返回值>0      a 排在 b 前

當函式返回值<0      b 排在 a 前
 

int,char ,double 等簡單型別的

bool cmp(const void *a,const void *b )

{
    return *(int *)a-*(int *b);    //降序排列
    /********
    (int *)為強制型別轉換
    根據需要改寫
    *********/
    
}

2.sort

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

/*char double float...也可以*/

結構體型別

1.sort 

一級結構體

struct node{
    int x;
    char y;

//方法一:
    bool operator <(const node &a)    //運算子過載
    {
        return x>a.x;    //降序排列
    }
    
//方法二:
    bool operator <(const node &a, const node &b)
    {
        return a.y>b.y;
    }
};


vector<node> v;

sort( v.begin(),v.end() );

//方法三
    bool cmp(node &a,node &b)
    {
        return a.x>b.x;
    }
vector<node> v;

sort( v.begin(),v.end(),cmp );

 二級結構體

struct node 
{
    int num;   
    int id;
};

bool cmp(node &a,node &b)
{
    if(a.num!=b.num)
        return a.num>b.num;    //num大的在前
    else
        return a.id<b.id;      //num相同的,id小的在前
}

sort( ,  , cmp );

 

2.qsort 

struct node{
	int id;
	int flag;
	int pos;
};


//一級結構體比較
bool cmp1(const void *a,const void *b)
{
	return (*(struct node *)a).pos>(*(struct node *)b).pos?1:0;  //從小到大排序 
}



int cmp2(const void *a,const void *b)
{
	return (*(struct node *)a).id-(*(struct node *)b).id;
}


//二級結構體比較

int cmp1(const void *a,const void *b)
{
    if((*(struct node *)a).pos!=(*(struct node *)b).pos)
	    return (*(struct node *)a).pos-(*(struct node *)b).pos;		//從小到大排序 
    else
        return  (*(struct node *)a).id-(*(struct node *)b).id;      //pos 相等的 比較 id
}

3.sort 和 qsort 皆可

可以直接呼叫庫函式    #include<functional>

equal_to

實現x == y的函式物件 
(類模板)

not_equal_to

實現x != y的函式物件 
(類模板)

greater

實現x > y的函式物件 
(類模板)

less

實現x < y的函式物件 
(類模板)

greater_equal

實現x >= y的函式物件 
(類模板)

less_equal

實現x <= y的函式物件 
(類模板)

字串型別的

struct node {
char str[100];
int num;
};

int cmp1(const void *a, const void *b)
{
    return strcmp((struct node *)a->str,(struct node *)b->str;
}

qsort( , , , cmp);

  若c++中為string 型別資料則直接使用大於小於即可