Summary of usage examples of the qsort function in C language

  • 2020-04-02 02:42:05
  • OfStack

This example summarizes the common usage of the qsort function in C language, which is of great practical value. Share with you for your reference. Specific analysis is as follows:

The qsort function in C is included in < Stdlib. H > In the header file, the sorting in this article is used from small to large sort.

Sort an array of type int


int num[100]; 

int cmp ( const void *a , const void *b ) 
{ 
  return *(int *)a - *(int *)b; 
} 
qsort(num,100,sizeof(num[0]),cmp); 

Sort array of char type (same as int type)


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

qsort(word,100,sizeof(word[0]),cmp); 

Sort arrays of type double (special attention)


double in[100]; 

int cmp( const void *a , const void *b ) 
{ 
  return *(double *)a > *(double *)b ? 1 : -1; 
} 
qsort(in,100,sizeof(in[0]),cmp);

Four, the structure of the first order  


struct In 
{ 
  double data; 
   int other; 
}s[100] ; 

int cmp( const void *a ,const void *b) 
{ 
  return (*(struct In *)a)->data > (*(struct In *)b)->data ? 1 : -1; 
} 
qsort(s,100,sizeof(s[0]),cmp); 

  Fifth, the structure of the secondary order  


struct In 
{ 
  int x; 
  int y; 
}s[100]; 

//Sort by x from small to large, sort by y from large to small when x is equal
int cmp( const void *a , const void *b ) 
{ 
  struct In *c = (struct In *)a; 
  struct In *d = (struct In *)b; 
  if(c->x != d->x) return c->x - d->x; 
  else return d->y - c->y; 
} 
qsort(s,100,sizeof(s[0]),cmp); 

  Sort the strings


struct In 
{ 
  int data; 
  char str[100]; 
}s[100]; 

//Sort by the lexicographical order of the string STR in the struct
int cmp ( const void *a , const void *b ) 
{ 
  return strcmp( (*(struct In *)a)->str , (*(struct In *)b)->str ); 
} 
qsort(s,100,sizeof(s[0]),cmp); 

I believe that the examples described in this paper have certain reference value to the learning of C program design.


Related articles: