qsort_demo.c 555 B

1234567891011121314151617181920212223
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. // 整数的比较函数, 用作 sort() 函数的排序函数
  4. int compare_ints(const void* a, const void* b){
  5. int arg1 = *(const int*)a;
  6. int arg2 = *(const int*)b;
  7. if (arg1 < arg2) return -1;
  8. if (arg1 > arg2) return 1;
  9. return 0;
  10. }
  11. int main(void){
  12. int ints[] = { -2, 99, 0, -743, 2, -69820, 4 };
  13. int size = sizeof ints / sizeof *ints;
  14. qsort(ints, size, sizeof(int), compare_ints);
  15. for (int i = 0; i < size; i++) {
  16. printf("%d ", ints[i]);
  17. }
  18. printf("\n");
  19. }