Search code examples
arrayscsortingcomparisonqsort

Can you qsort part of an array?


I'd like to qsort the first 100 elements in an integer array and leave the remaining elements untouched.

I'm currently trying to do this with the following call:

int cmpfunc(const void *a, const void *b)
{
  int xi = *(const int *) a;
  int yi = *(const int *) b;
  
  return (xi - yi);
}

int my_array[100+some_size];
memset(my_array, 0, sizeof(my_array));
qsort(my_array, 100, sizeof(int), cmpfunc);

However, I'm getting a segmentation fault. Is sorting the first x values of an array in C possible?


Solution

  • From the point of view of the qsort function it makes no difference if there are any more array elements after the first 100, since it only gets a pointer to the start of the array, and the number of elements after the starting pointer.

    So, yes, assuming it's possible to sort an array with 100 elements, it's also possible to sort the first 100 elements of a larger array.