First, 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);
Second, sort the array of char types (same as int type)
Char word[100];
int cmp (const void *a, const void *b)
{
return * (char *) A-* (int *) b;
}
Qsort (Word,100,sizeof (word[0]), CMP);
Third, sort the array of double type
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);
Iv. sequencing of structural bodies
struct Sample
{
Double data;
int other;
}S[100]
Sort by data value from small to general structure
int cmp (const void *a, const void *b)
{
Return (* (sample *) a). Data > (* (sample *) b). Data? 1:-1;
}
Qsort (S,100,sizeof (s[0]), CMP);
Five, the structure of the two-level ranking
struct Sample
{
int x;
int y;
}S[100];
Sort by x from small to large, when x is equal by y from largest to smallest
int cmp (const void *a, const void *b)
{
struct Sample *c = (sample *) A;
struct Sample *d = (sample *) b;
if (c->x! = d->x) return c->x-d->x;
else return d->y-c->y;
}
Qsort (S,100,sizeof (s[0]), CMP);
Six, sort the string
struct Sample
{
int data;
Char str[100];
}S[100];
Sort by the dictionary order of the string str in the struct
int cmp (const void *a, const void *b)
{
Return strcmp ((* (sample *) a). STR, (* (sample *) b). str);
}
Qsort (S,100,sizeof (s[0]), CMP);
Append a full point code, sort the two-dimensional array of strings:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Char s[2001][1001];
int cmp (const void *a, const void *b) {
Return strcmp ((char *) A, (char *) b);
}
int main () {
int i,n;
scanf ("%d", &n);
GetChar ();
for (i=0;i<n;i++) gets (S[i]);
Qsort (S,n,1001*sizeof (char), CMP);
For (i=0;i<n;i++) puts (s[i]);
return 0;
}
A brief discussion on the fast ordering of different types of data by Qsort function