[英]QSORT on array in C?
If I have an array like this: 如果我有这样的数组:
2, 4, 6, 0, 0, 0, 0, 0, 0
qsort(arrNumbers, 3, sizeof(int), compare)
do the job? qsort(arrNumbers, 3, sizeof(int), compare)
做这项工作吗? EDIT: My compare function is: 编辑:我的比较功能是:
int comp(const int * a, const int * b)
if(a==b)
{
return 0;
}
else
{
if(a<b)
{
return -1;
}
else
{
return 1;
}
}
Does it seem right? 看起来对吗?
Yes. 是。
Yes. 是。 *
*
Yes. 是。
compare()
appropriately.
compare()
。
Why don't you try it and see that it works as you expect? 为什么不尝试一下,看看它能按预期工作?
Explanation: the qsort
function only gets a pointer to the array, which does not say how long the array is. 说明:
qsort
函数仅获得指向数组的指针 ,而没有说明数组的长度。 That's why you have to pass the size as well. 这就是为什么您还必须通过大小。 In your function call you claim that the array is three
int
s long, and that's all the qsort
function can be sure of. 在函数调用中,您声称该数组的长度为3
int
,这就是qsort
函数可以确定的全部。 It will not access anything beyond that limit. 它不会访问超出该限制的任何内容。
The full signature is: 完整的签名是:
void qsort(
void * base,
size_t num,
size_t width,
int (__cdecl *compare )(const void *, const void *)
);
To sort a specific contiguous range of the array, you just pass in a different base
(pointer to starting element for the range) and num
(number of elements in the range). 要对数组的特定连续范围进行排序,只需传递一个不同的
base
(指向该范围的起始元素的指针)和num
(该范围中的元素数)。
是的,如果您指定3,则只会对前3个元素进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.