Adam
Adam

Reputation: 41

sort multidimensional array with qsort in C

I'm trying to sort multidimensional array with qsort, but the result is nonsense..

My code (excerpt):

#include <stdio.h>
#include <stdlib.h>

int srovnejVelikost(const void *p1, const void *p2) {
    const long int (*a)[5] = p1;
    const long int (*b)[5] = p2;
    return ((*a)[0] + (*a)[1] - (*b)[0] - (*b)[1]);
}

long int nadrze[200000][5];

[values added into the array here]

qsort (nadrze, 200000, sizeof(nadrze[0]), srovnejVelikost);

It should sort nadrze[] according to the result of (nadrze[a][0] + nadrze[a][1] - nadrze[b][0] - nadrze[b][1]).... all 5 elements moved

Thanks for your help. It is most appreciated.

Upvotes: 0

Views: 745

Answers (2)

Timothy Brown
Timothy Brown

Reputation: 2280

If your sort criteria is truly nadrze[a][0] + nadrze[a][1] - nadrze[b][0] - nadrze[b], I find the following example to represent it:

#include <stdio.h>
#include <stdlib.h>

#define max_i 5
#define max_j 5

int srovnejVelikost(const void *p1, const void *p2) {
    const long int *a = p1;
    const long int *b = p2;
    return ((a[0] + a[1]) - (b[0] + b[1]));
}

int main(int argc, char **argv)
{
    int i = 0;
    int j = 0;
    long int nadrze[max_i][max_j];
    long int d = 0;

    printf("Before\n");
    for (i = 0; i < max_i; ++i) {
            d = (nadrze[i][0] + nadrze[i][1]);
            printf("i: %d %d\n",i, d);
    }

    qsort(nadrze, max_i, sizeof(long int)*max_j, srovnejVelikost);

    printf("After\n");
    for (i = 0; i < max_i; ++i) {
            d = (nadrze[i][0] + nadrze[i][1]);
            printf("i: %d %d\n",i, d);
    }


    return(EXIT_SUCCESS);

} 

You can expand out max_i and max_j as your case needs. I just used defines as I was testing.

Also note, I coded it as (a[0] + a[1]) - (b[0] + b[1]) as this is equivalent to a[0] +a[1] - b[0] - b[1] and it makes more sense as I read it for a comparator.

You need to pass the whole row to qsort, which I do by saying the width is `sizeof(ling int)*max_j, which is 5 in your case.

Does this make sense?

(The qsort comparison function doesn't care if you pass it one int or an array, it is up to you on how you deal with it. So watch our you don't access beyond what your meant to.)

Upvotes: 1

uSeemSurprised
uSeemSurprised

Reputation: 1834

int arr[10][100];
for(i=0;i<10;i++){
    qsort(arr[i],------,-----,----);
}

It is multidimensional array you can sort one at a time, qsort cannot sort all at the same time.

Upvotes: 0

Related Questions