How to take values in one cell of 2D array by keeping other cell value constant and then How to apply Qsort?

StackOverflow https://stackoverflow.com/questions/21702740

Domanda

I have two arrays:

arr[] = {1,2,3,4,5,6};  
arr1[] = {16,13,11,18,19,10};

and I wish to store these two arrays in 2D array such that 2D array looks like:

A[6][2] = {{1,16},{2,13},{3,11},{4,18},{5,19},{6,10}};

and then I wish to perform qsort on column's values such that now array looks like:

A[6][2] = {{6,10},{3,11},{2,13},{1,16},{4,18},{5,19}};

I tried alot but failed to do this. So help me to solve this problem.
I'm beginner in C, so please don't mind if my question is lame.

È stato utile?

Soluzione

sample

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

typedef int (*pair)[2];

pair zip(int n, int a1[n], int a2[n]){
    pair p = malloc(n * sizeof(*p));
    for(int i = 0; i < n ; ++i){
        p[i][0] = a1[i];
        p[i][1] = a2[i];
    }
    return p;
}

int cmp(const void *a, const void *b){
    pair x = (pair)a;
    pair y = (pair)b;
    return x[0][1] < y[0][1] ? -1 : x[0][1] > y[0][1];
}

int main(void){
    int arr[] = {1,2,3,4,5,6};
    int arr1[] = {16,13,11,18,19,10};
    int size = sizeof(arr)/sizeof(*arr);
    pair A = zip(size, arr, arr1);

    for(int i = 0;i<size;++i){
        printf("{");
        printf("{%d, %d}", A[i][0], A[i][1]);
        if(i!=size-1)
            printf(",");
        else
            printf("}\n");
    }
    qsort(A, size, sizeof(*A), cmp);
    for(int i = 0;i<size;++i){
        printf("{");
        printf("{%d, %d}", A[i][0], A[i][1]);
        if(i!=size-1)
            printf(",");
        else
            printf("}\n");
    }
    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top