Seven qsort sorting methods
<In this article, sorting is performed in ascending order.>
I. Sorting int-type Arrays
Int num [100];
Sample:
Int CMP (const void * a, const void * B)
{
Return * (int *) A-* (int *) B;
}
Qsort (Num, 100, sizeof (Num [0]), CMP );
2. Sort char array (same as int type)
Char word [100];
Sample:
Int CMP (const void * a, const void * B)
{
Return * (char *) A-* (char *) B;
}
Qsort (word, 100, sizeof (word [0]), CMP );
3. Sort arrays of the double type (special note)
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 );
4. sorting the struct at a level
Struct in
{
Double data;
Int Other;
} S [100]
// Sort by data values from small to large struct. There are many types of sorting key data in the Structure Body. refer to the example above to write
Int CMP (const void * a, const void * B)
{
Return (* (in *) A)-> DATA> (* (in *) B)-> data? 1:-1;
}
Qsort (S, 100, sizeof (s [0]), CMP );
5. List struct
Struct in
{
Int X;
Int y;
} S [100];
// Sort by X from small to large, and sort by Y from large to small when X is equal
Int CMP (const void * a, const void * B)
{
Struct in * c = (in *);
Struct in * D = (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 );
6. Sort strings
Struct in
{
Int data;
Char STR [100];
} S [100];
// Sort the string 'str' in alphabetical order.
Int CMP (const void * a, const void * B)
{
Return strcmp (* (in *) A)-> STR, (* (in *) B)-> Str );
}
Qsort (S, 100, sizeof (s [0]), CMP );
VII. CMP for convex hull Calculation
Int CMP (const void * a, const void * B) // The Key CMP function sorts all vertices and rotation angles except 1.
{
Struct point * c = (point *);
Struct point * D = (point *) B;
If (calc (* C, * D, P [1]) <0) return 1;
Else if (! Calc (* C, * D, P [1]) & DIS (c-> X, C-> Y, P [1]. x, p [1]. y) <DIS (D-> x, D-> Y, P [1]. x, p [1]. y) // if it is in a straight line, place the far one in front of it.
Return 1;
Else return-1;
}
:
Load the header file "iostream" in C ++"
In C, the qsort function is included in the header file of <stdlib. h>, and strcmp is included in the header file of <string. h>.