qsort函數輔助函數compare函數的編寫


qsort的第四個參數,輔助函數compare的關於不同排序對象的不同寫法:

一、對int類型數組排序

int num[100];
int compare(const void *a, const void *b)
{
  return *(int *)a - *(int *)b;
}

 

二、對char類型數組排序(同int類型)

char word[100];
int compare(const void *a, const void *b)
{
  return *(char *)a - *(char *)b;
}

 

三、對double類型數組排序

double array[100];
int compare(const void *a, const void *b)
{
  return *(double *)a > *(double *)b ? 1 : -1;
}

注意qsort第三個參數是sizeof(array[0])。

四、對結構體一級排序

typedef struct node
{
    double data;
    int other;
}Node;
array[100];

int compare(const void *a, const void *b)
{
    return ((Node *)a)->data > ((Node *)b)->data ? 1 : -1;
}

 

五、對結構體二級排序

typedef struct node
{
    int x;
    int y;
}Node;
Node array[100];
//按照x從小到大排序,當x相等時按照y從大到小排序 
int compare(const void *a, const void *b)
{
    Node *p1 = (Node *)a;
    Node *p2 = (Node *)b;
    if (p1->x != p2->x)
        return p1->x - p2->x;
    else
        return p1->y - p2->y;
}

 

六、對字符串進行排序

typedef struct node
{
    int other;
    char string[100];
}Node;
Node array[100];
//按照結構體中字符串string的字典順序排序 
int compare(const void * a, const void * b)
{
    return strcmp(((Node *)a)->string, ((Node *)b)->string);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM