C qsort() with dynamic n by 2 multi-dimensional array

前端 未结 4 1777
情深已故
情深已故 2020-12-15 01:54

First, I defined a dynamic array with 2 columns and 10 row. The integer number is set to 10 here just for example.

int** array;
int number = 10;         


        
4条回答
  •  盖世英雄少女心
    2020-12-15 02:22

    I came across this thread in search of a ditto problem of mine, and I lastly end-up doing the below thing.

    static int compareMatrixElements(const void *p1, const void *p2)
    {
        return ((*(int const *) p1) - (*(int const *) p2));
    }
    
    void sortMatrix(int** matrix, int r, int c)
    {
        int sort_matrix[r][c];
    
        for(int i = 0; i < r; i++) {
    
            memcpy(sort_matrix[i], matrix[i], c * sizeof(int));
        }
    
        qsort(sort_matrix, r*c, sizeof(int), compareMatrixElements);
    
        for(int i = 0; i < r; i++) {
    
            memcpy(matrix[i], sort_matrix[i], c * sizeof(int));
        }
    }
    

    In the above code of mine I used qsort API directly, one can use this api or any other sort algo on a contiguous memory, but what If you are having a matrix whose rows are pointer to the memory of its columns (like in my case as well as described in the question of this thread). Hence I copied such matrix into a contiguous memory, ran sort on that contiguous memory and copied back the sorted elements to the matrix.

    The above solution worked for me, I thought it might be helpful others so I posted it, suggest any improvement for the same.

提交回复
热议问题