当为一维数组时
/* qsort example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort */
int values[] = { 40, 10, 100, 90, 20, 25 };
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++)
printf ("%d ",values[n]);
return 0;
}
当为二维数组时
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int cmp(const void *a,const void *b)
{
int *c = (int *)a;
int *d = (int *)b;
if(*c != *d)
return *c - *d;
return *(d+1) - *(c+1);
}
int main()
{
int i, j;
int a[6][2]={{1,6},{1,7},{3,9},{3,9},{4,10},{4,12}};
for(i=0;i<6;i++)
{
for(j=0;j<2;j++)
printf("%d ",a[i][j]);
printf("\n");
}
printf("\n");
qsort(a,6,sizeof(a[0]),cmp);//sizeof(int*)
for(i=0;i<6;i++)
{
for(j=0;j<2;j++)
printf("%d ",a[i][j]);
printf("\n");
}
system("pause");
return 0;
}
其次cmp也有其他的写法
int cmp(const void *str1, const void *str2)
{
const char **tmp1 = *(char**)str1;
const char **tmp2 = *(char**)str2;
int ret = strcmp(tmp1[0], tmp2[0]);
if (ret == 0) {
return strcmp(tmp1[1], tmp2[1]);
}
return ret;
}
int cmp(const void* _a, const void* _b) {
int **a = (int**)_a, **b = (int**)_b;
return (*b)[0] - (*a)[0] ? (*b)[0] - (*a)[0] : (*b)[1] - (*a)[1];
}