Search code examples
carrayssortingqsort

Sort everything except first element, qsort C


I do have something odd. I would like to sort an array of many elements by colour on a chess board. This is quite easy (see attached code), so if x%2==y%2 is true, then it's black, if not it's white. But that's not the problem. I do have one element at the front of the array, which is a little bit different (need that for some calculation later) and needs to stay where it is.

Is it possible to sort an array without touching the first element?

int compareColour(const void * fs1, const void * fs2) {
    Field *orderA = (Field *)fs1;
    Field *orderB = (Field *)fs2;

    bool isBlackB = ((orderA->x%2)==(orderA->y%2));
    bool isBlackA = ((orderB->x%2)==(orderB->y%2));
    return (isBlackB - isBlackA);
}

void sortByColour() {
    qsort(fieldArr,(size_t) countFields, sizeof(Field), compareColour);
}

Solution

  • You could just pass a pointer to the second element (i.e., the one at index 1) instead of the array's beginning and reduce the count by one, as @ user3386109 commented:

    qsort(fieldArr + 1, (size_t) (countFields - 1), sizeof(Field), compareColour);
    /* 2nd element---^ */
    /* Reduce the count ----------------------^ */