执行排序的C库函数 [英] C library function to perform sort
本文介绍了执行排序的C库函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C 标准库中是否有可用的库函数来进行排序?
Is there any library function available in C standard library to do sort?
推荐答案
qsort()
是您正在寻找的函数.您可以使用指向数据数组的指针、该数组中的元素数量、每个元素的大小和一个比较函数来调用它.
qsort()
is the function you're looking for. You call it with a pointer to your array of data, the number of elements in that array, the size of each element and a comparison function.
它发挥了它的魔力,并且您的数组就地排序.一个例子如下:
It does its magic and your array is sorted in-place. An example follows:
#include <stdio.h>
#include <stdlib.h>
int comp (const void * elem1, const void * elem2)
{
int f = *((int*)elem1);
int s = *((int*)elem2);
if (f > s) return 1;
if (f < s) return -1;
return 0;
}
int main(int argc, char* argv[])
{
int x[] = {4,5,2,3,1,0,9,8,6,7};
qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);
for (int i = 0 ; i < 10 ; i++)
printf ("%d ", x[i]);
return 0;
}
这篇关于执行排序的C库函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文