简体   繁体   English

内置函数,用于在C中对数组进行排序

[英]Built in functions for sorting arrays in C

Are there any built in functions in C programming language for sorting arrays? C编程语言中是否有用于排序数组的内置函数? Or do I have to write my own functions? 或者我必须编写自己的函数?

Check out qsort 看看qsort

Syntax: 句法:

#include <stdlib.h>
void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );

Description: 描述:

The qsort() function sorts buf (which contains num items, each of size size) using Quicksort. qsort()函数使用Quicksort对buf(包含大小为num的num项qsort()排序。 The compare function is used to compare the items in buf. 比较函数用于比较buf中的项目。 compare should return negative if the first argument is less than the second, zero if they are equal, and positive if the first argument is greater than the second. 如果第一个参数小于第二个参数,则compare应返回负数,如果它们相等则返回零,如果第一个参数大于第二个参数,则返回正数。 qsort() sorts buf in ascending order. qsort()按升序对buf进行排序。

You can use qsort in stdlib.h . 您可以在stdlib.h使用qsort It is quick-sort algorithm, which has average time complexity of O(nlogn) and worst case complexity of O(n 2 ). 它是快速排序算法,其平均时间复杂度为O(nlogn),最差情况复杂度为O(n 2 )。 The C99 standard and even the newer C11 Standard doesn't mandate the implementation or time complexity of the function. C99标准甚至更新的C11标准都没有规定功能的实现或时间复杂性。 However, it is very likely that common implementation will use algorithm that yields average case O(nlogn) time complexity (which is optimal for sorting by comparison). 然而,通常的实现很可能会使用能够产生平均情况O(nlogn)时间复杂度的算法(通过比较对于排序是最佳的)。

You can use this to sort any kind of array (even struct ) - but you must provide a comparison function to compare between 2 elements of the array. 您可以使用它来排序任何类型的数组(甚至struct ) - 但您必须提供比较函数来比较数组的2个元素。

qsort is well known. qsort是众所周知的。 There are others also like heapsort, mergesort etc. Please check the link for more details. 还有其他人也喜欢heapsort,mergesort等。请查看链接了解更多详情。

Please note that all of them take comparison functions as input, making them easily usable with native as well as user created data types. 请注意,它们都将比较函数作为输入,使它们可以轻松地用于本机和用户创建的数据类型。

Yes: qsort . 是的: qsort It's in stdlib.h . 它在stdlib.h

Simple syntax : 语法简单:

int function (const void * a, const void * b) {return ( *(int*)a-(int*)b);}
`qsort(arr_name , sizeofarray , sizeof(int), function);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM