qsort 函数笔记

qsort 函数笔记

函数声明

void qsort(void *base, size_t nitems, size_t size, int (*compare)(const void *, const void*));

说明

  • stdlib.h
  • 无返回值
  • base 指向要排序的数组的第一个元素的指针
  • nitems 由 base 指向的数组中元素的个数
  • size 数组中每个元素的大小,以字节为单位
  • compare 用来比较两个元素的函数

比较函数 compare

  • 比较函数返回值的结果对 qsort 函数运行的影响不做讨论,返回值情况只有大于0、小于0、等于0三种情况,相当于冒泡排序最内层循环中的 if 语句,具体情况参考示例代码;
  • const void * 声明一个引用类型为 void * 的常量指针,它可以指向任何类型的 常量

示例代码

#include <stdio.h>
#include <stdlib.h>

int cmp (const void * a, const void * b)
{
    return *(int*)a-*(int*)b;
    /*从小到大*/
}

int main()
{
	/*示例输入:9 1 2 3 4 5 6 7 8 9*/
	int n;
	int a[100];
	int i,j;

	scanf("%d", &n);
	for (i=0; i<n; i++) {
        scanf("%d", &a[i]);
	}

	qsort(a, n, sizeof(int), cmp);

	for (i=0; i<n; i++) {
        printf("%d ", a[i]);
	}
	putchar('
');

	return 0;
}

by sdust weilinfox
转载请注明原文地址:https://www.cnblogs.com/weilinfox/p/12238279.html