An example of the usage of qsort functions in C language

  • 2020-06-01 10:25:52
  • OfStack

An example of the usage of qsort functions in C language

Quicksort is one of the most commonly used sorting algorithms. There are also quicksort functions in the standard library of C language.

The qsort function is contained in < stdlib.h > In the

The qsort function is declared as follows:

void qsort(void * base,size_t nmemb,size_t size ,int(*compar)(const void *,const void *));

Parameter description:

base, the array to sort
nmemb, the number of elements in an array
size, the memory space occupied by each array element, can be obtained using the sizeof function
compar, a pointer to a function is also known as a function pointer. This function is used to compare two array elements. When the first parameter is greater than, equal to, or less than the second parameter, it displays positive, zero, and negative values respectively.

Here are some examples:

void main(void) 
  int i; 
  int a[10]={0,1,2,3,4,5,6,7,8,9}; 
  char b[10]={'a','b','c','d','e','f','g','h','i','j'}; 
  double c[10]={0.1,0.2,0.9,0.5,0.3,0.6,0.7,0.8,1.1,1.2}; 
  int cmp1(const void * a,const void * b) 
    return (*(int*)a-*(int*)b);//a>b  Return when the  
  int cmp2(const void * a,const void *b) 
  int cmp3(const void * a,const void * b) 
    if(fabs(*(double*)a-*(double *)b)<1*exp(-20)) 
      return 0; 
  qsort(a,10,sizeof(int),&cmp1);// For function Pointers (Pointers to functions), directly pass in the function name and the function name & 
                 // The operation is ok, because the function is called at the address of the function  
    printf("%d ",a[i]); 
    printf("%c ",b[i]); 
    printf("%lf ",c[i]); 

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!

Related articles: