1. Basic usage of qsort
Routine | Required Header | Compatibility |
---|---|---|
qsort | <stdlib.h> and <search.h> | ANSI, Win 95, Win NT |
usage:
void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );
Four parameters:
1.void*base: the address of the array to be sorted, that is, the array name
2.size_t num: the number of elements to be sorted in the array
3.size_t width: the number of bytes occupied by each element
4.int (__cdecl *compare )(const void *elem1, const void *elem2): custom function pointer, used to determine the order of sorting (users need to define a comparison function), the default sorting method is ascending
return value:
Return Value | Description |
---|---|
< 0 | elem1 less than elem2 |
=0 | elem1 equivalent to elem2 |
>0 | elem1 greater than elem2 |
1. A simple sorting problem for sorting the int array
, here is implemented with the qsort function
#include<stdio.h>
#include<stdlib.h>
int cmp(const void* p1, const void* p2)//形参格式不能改
{
return((*(int*)p2)-(*(int*)p1)); //将数组元素降序排列
// return((*(int*)p1) - (*(int*)p2); 将数组元素升序排列
}
int main()
{
int a[40], n, i;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
qsort(a, n, sizeof(a[0]), cmp);
for (i = 0; i < 5; i++)
{
printf("%d ", a[i]);
}
}
2. Sort the character string
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int cmp(const void* p1, const void* p2)
{
return((*(char*)p1) - (*(char*)p2));
}
bool b(char* s, char* t)
{
int ls = strlen(s);
int lt = strlen(t);
if (ls != lt)
{
return false;
}
qsort(s, ls, sizeof(s[0]), cmp);
qsort(t, lt, sizeof(t[0]), cmp);
if (strcmp(s, t) == 0)
{
return true;
}
}
int main()
{
char s[40], t[40];
gets(s);
gets(t);
if (b(s, t))
{
printf("true");
}
else
{
printf("false");
}
}
3. Sort the char array.
Similar to the int array type, you can convert it to char* during type conversion.
Four. Sort the double array
#include<stdio.h>
#include<stdlib.h>
int cmp(const void* p1, const void* p2)
{
double* a = (double*)p1;
double* b = (double*)p2;
return *a > * b ? 1 : -1;
}
int main()
{
double a[40];
qsort(a, 40, sizeof(a[0]), cmp);
}
The ternary operator must be used for floating point or double type, because if you use subtraction like integer type, if it is two close numbers, it may return a small decimal number (greater than -1, less than 1 ), and the return value of cmp is int type, so the decimal will be returned to 0, the system considers it to be equal, and loses the original size relationship