c 自带的qsort函数

C语言 qsort

C 自带了一个排序函数qsort, 使用时要定义一个compare方法。

下面是一个例子:

复制代码
/* 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 <stdlib.h>
#include <stdio.h>

typedef struct _block{
  int att1;
  int att2;    
}Block;

int compare(const void *a, const void *b)
{
  int  aa = ((Block *)a)->att1;
  int bb = ((Block *) b)->att1;
  if (aa > bb) return 1;
  else if (aa < bb) return -1;
  else return 0;  
}

int main()
{
  int n;
  Block b[3];
  b[0].att1= 3; b[0].att2=3;
  b[1].att1 =8; b[1].att2=8;
  b[2].att1 = 5; b[2].att2=5;

  qsort(b, 3, sizeof(Block), compare);
  for (n=0; n<3; n++){
     printf("%d  %d\n", b[n].att1, b[n].att2);
  }

  return 0;
}
复制代码
要想按照降序排列,只需要修改compare函数的返回值就行了。

 
复制代码

猜你喜欢

转载自blog.csdn.net/momo_mo520/article/details/80723167