How to use the quicksort function in the VC library function

  • 2020-04-02 01:29:04
  • OfStack

Function prototype:
Void qsort(void *base,size_t num,size_t width,
Int (s)(const void *, const void *);

The first is the address of the array, the second is the size of the array, the third is the number of bytes per element in the array, and the last is a function pointer that shows how to compare the elements in the array.

The header file # include < Stdlib. H >
The following four cases are explained in terms of int and other integer data, double and other floating point data, structs and classes, as specified.

Instance 1, sort integer data such as int


int cmp(const void *x, const void *y)
{
 return *(int*)x - *(int*)y;
}
qsort(a, MAXN, sizeof(a[0]), cmp); 

The MAXN is the size of the array, the same as below

Instance 2 sorts floating-point Numbers such as double


int cmpDouble(const void *x, const void *y)
{
 return (*(double*)x > *(double*)y ? 1 : -1);
}
qsort(a, n, sizeof(a[0]), cmpDouble);

Example 3. Sort complex data such as structure and class
Such as

struct Student
{
 char szName[30];
 int  nAge;
};

Sort by age, same age and then by name.

int cmpStudent (const void *x, const void *y)
{   //First make the pointer conversion, and then compare as required
 Student *pNodex = (Student*)x, *pNodey = (Student*)y;
 if (pNodex->nAge != pNodey->nAge)
  return pNodex->nAge - pNodey->nAge;
 else
  return strcmp(pNodex->szName, pNodey->szName);
}
qsort(a, n, sizeof(a[0]), cmpStudent);

Instance 4, sort as specified.
For example, the string "AajkuKdYUBCDwyz" with only uppercase and lowercase letters should be sorted.

int cmp1(const void *x, const void *y)
{
 char *pcx = (char*)x, *pcy = (char*)y;
 bool flag1 = *pcx >= 'A' && *pcx <= 'Z';
 bool flag2 = *pcy >= 'A' && *pcy <= 'Z';
 if(flag1 == flag2)    //If it's all uppercase or all lowercase
  return *pcx - *pcy;
 else                  //Otherwise, whoever capitalizes the letter has a smaller weight.
  return flag1 ? -1 : 1;
}
int main()
{
 char szText[] = "AajkuKdYUBCDwyz";
 qsort(szText, strlen(szText), sizeof(szText[0]), cmp1);
 printf("%sn", szText);
 return 0;
}


Related articles: