0

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?
  2. Would qsort(arrNumbers, 3, sizeof(int), compare) do the job?
  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?

5
  • 6
    Here's a novel idea: put it in a C program and see what happens! Commented Nov 13, 2011 at 22:43
  • 1
    what does the manpage say? Commented Nov 13, 2011 at 22:43
  • Have you tried it? It should work, and it's not hard to try. Commented Nov 13, 2011 at 22:44
  • 5
    To the empiricists: the trouble is that trying does not prove anything if you take possible UB into account. Any 'evidence' could be coincidental. I'd say the standards documentation is a bit stronger Commented Nov 13, 2011 at 22:46
  • 1
    Just trying it is not enough. Its a sign that maybe it worked by design, maybe there was undefined behavior anywhere that coincidentally caused the program to output the expected answer, and maybe something else. So it's good to know the background, especially when working with C or C++. Commented Nov 13, 2011 at 22:53

4 Answers 4

7

Yes.

Yes.*

Yes.


* Assuming you define compare() appropriately.

Sign up to request clarification or add additional context in comments.

1 Comment

that's a great (sick) caveat!
2

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. That's why you have to pass the size as well. In your function call you claim that the array is three ints long, and that's all the qsort function can be sure of. It will not access anything beyond that limit.

Comments

2

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).

Comments

1

Yes if you specify 3 in your case it will only sort the first 3 elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.