以降序输出数组的索引

时间:2017-09-07 17:28:40

标签: c

我使用以下quicksort函数按降序对任何给定数组进行排序:

int sorting (const void * a, const void * b)
{
    return ( *(double*)a < *(double*)b );
}
int main(int argc, char *argv[]) {

    int n;
    double values[] = { 88.54, 56.65, 100.13, 2.091, 25.223 };
    qsort(values, 5, sizeof(double), sorting);
    for( n = 0 ; n < 5; n++ ) {
        printf("%f ", values[n]);
    }
    return(0);

}

除了按降序输出值外,我还想输出相应的indices。例如,对于给定的values[]数组,我会得到[2,0,1,4,3],表示索引2具有最大值,索引0具有第二大值,依此类推。如何修改上面的代码?

谢谢

1 个答案:

答案 0 :(得分:1)

将值与struct中的索引相结合,对它们进行排序,并打印索引以及值:

struct ind_val {
    int index;
    double value;
};
int sorting_ind_val (const void * a, const void * b) {
    double lhs = ((struct ind_val*)a)->value;
    double rhs = ((struct ind_val*)b)->value;
    if (lhs < rhs)
        return 1;
    if (lhs > rhs)
        return -1;
    return 0;
}
...
double values[] = { 88.54, 56.65, 100.13, 2.091, 25.223 };
struct ind_val pair[5];
for (int i = 0 ; i != 5 ; i++) {
    pair[i].index = i;
    pair[i].value = values[i];
}
qsort(pair, 5, sizeof(struct ind_val), sorting_ind_val);
for (int i = 0 ; i != 5 ; i++) {
    printf("%d: %f\n", pair[i].index, pair[i].value);
}

Demo.

2: 100.130000
0: 88.540000
1: 56.650000
4: 25.223000
3: 2.091000