简体   繁体   English

使用qsort()在ANSI C中对二维数组进行排序

[英]Sorting 2-dimensional array in ANSI C with qsort()

I have a two dimensional array and want to sort both rows depending on the order of the elements in the first row: 我有一个二维数组,并希望根据第一行中元素的顺序对两行进行排序:

i start with: 我开始:

row1: { 4, 3, 1, 5, 0} 第1行:{4,3,1,5,0}

row2: { 7, 8, 9, 1, 2} 第2行:{7,8,9,1,2}

and the result should be: 结果应该是:

row1: { 0, 1, 3, 4, 5} 第1行:{0,1,3,4,5}

row2: { 2, 9, 8, 7, 1} 第2行:{2,9,8,7,1}

QUESTION: Is it possible to achieve this, by using the qsort() function? 问题:是否可以通过使用qsort()函数实现此目的?

I think ,that way it could be done. 我想,就这样可以做到。

#include<bits/stdc++.h>
using namespace std;

int cmp(const void *a,const void *b) {
    return ((const int *)a)[0] - ((const int *)b)[0];
}

int main(int argc,char *argv[]){
    int list[10][2];
    printf("Before sorting\n");
    for(int i=0; i<10; i++){ 
        list[i][0] = rand()%31;
        list[i][1] = rand()%12;
        printf ("list[%d][0] = %d list[%d][1] = %d\n", i, list[i][0], i, list[i][1]);
    }
    printf("AFTER sorting\n");
    qsort(list,10,2*sizeof(int),cmp);
    for(int i=0; i<10; i++)
        printf ("list[%d][0] = %d list[%d][1] = %d\n", i, list[i][0], i, list[i][1]);
    return 0;
}

Output : 输出:

Before sorting
list[0][0] = 10 list[0][1] = 11
list[1][0] = 10 list[1][1] = 4
list[2][0] = 11 list[2][1] = 4
list[3][0] = 8 list[3][1] = 6
list[4][0] = 23 list[4][1] = 8
list[5][0] = 1 list[5][1] = 5
list[6][0] = 0 list[6][1] = 3
list[7][0] = 10 list[7][1] = 11
list[8][0] = 19 list[8][1] = 2
list[9][0] = 22 list[9][1] = 0
AFTER sorting
list[0][0] = 0 list[0][1] = 3
list[1][0] = 1 list[1][1] = 5
list[2][0] = 8 list[2][1] = 6
list[3][0] = 10 list[3][1] = 11
list[4][0] = 10 list[4][1] = 4
list[5][0] = 10 list[5][1] = 11
list[6][0] = 11 list[6][1] = 4
list[7][0] = 19 list[7][1] = 2
list[8][0] = 22 list[8][1] = 0
list[9][0] = 23 list[9][1] = 8

Not directly ... 不直接......

... but qsort() could sort vectors by each vector's first element. ...但是qsort()可以按每个向量的第一个元素对向量进行排序。

So the example data needed to be transposed and be converted into a fake 2d array, where the root pointer points to an array of pointers, with each pointer pointing to a row of the transposed original data. 因此,示例数据需要转置并转换为假的2d数组,其中根指针指向指针数组,每个指针指向转置的原始数据的行。

qsort() then is passed the root pointer and the compare function compares on the vectors' first element. qsort()然后传递根指针,比较函数比较矢量的第一个元素。 The vectors are passed to compare function by reference. 传递矢量以通过引用比较函数。

After sorting is done the result then needs to be converted the revers way as done prior to the call to qsort() . 排序完成后,结果需要按照调用qsort()之前的方式转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM