简体   繁体   English

QSORT在C中的数组上?

[英]QSORT on array in C?

If I have an array like this: 如果我有这样的数组:

2, 4, 6, 0, 0, 0, 0, 0, 0
  1. Is there a way I can use qsort by sorting just the first 3 elements, and leaving the rest untouched? 有没有一种方法可以通过仅对前3个元素进行排序而使其余部分保持不变来使用qsort?
  2. Would qsort(arrNumbers, 3, sizeof(int), compare) do the job? qsort(arrNumbers, 3, sizeof(int), compare)做这项工作吗?
  3. Does specifying the number of elements lower than the full array cause only that number of elements to become sorted? 指定少于完整数组的元素数量是否只会导致该数量的元素排序?

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. 是。


* Assuming you define 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.

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