The writing of compare function of qsort function auxiliary function

Source: Internet
Author: User

The fourth argument of Qsort, the compare of the auxiliary function, is the different ways of ordering objects:

First, sort an array of type int

int num[]; int Compare (constvoidconstvoid *b) {  return * (  int *) A-* (int *) b;}

Second, sort the array of char types (same as int type)

Char word[]; int Compare (constvoidconstvoid *b) {  return * (  Char *) A-* (int *) b;}

Third, sort the array of double type

double array[]; int Compare (constvoidconstvoid *b) {  return * (  Double *) a > * (double1 :-1;}

Note the third parameter of Qsort is sizeof (Array[0]).

Iv. sequencing of structural bodies

struct node{    double  data;     int Other ;} node;array[]; int Compare (constvoidconstvoid *b) {      return1 :-1;}

Five, the structure of the two-level ranking

typedefstructnode{intx; inty;} Node; Node array[ -];//Sort by x from small to large, when x is equal by y from largest to smallestintCompareConst void*a,Const void*b) {Node*P1 = (Node *) A; Node*P2 = (Node *) b; if(P1->x! = p2->x)returnP1->x-p2->x; Else        returnP1->y-p2->y;}

Six, sort the string

 typedef struct   node{ int   other;  char  string  [ 100  ];} Node; Node array[ 100  ];  //  by the dictionary order of string Strings in the struct body. int  compare (const  void  * A, const  void  * b) {  return  strcmp ((node *) a)->string , ((node *) b)->string ); 

The writing of compare function of qsort function auxiliary function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.