C 按降序输出数组的索引

C 按降序输出数组的索引,c,C,我使用以下快速排序函数按降序对任何给定数组进行排序: 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

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

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);

}
int排序(常量无效*a,常量无效*b)
{
返回(*(双*)a<*(双*)b);
}
int main(int argc,char*argv[]){
int n;
双值[]={88.54,56.65,100.13,2.091,25.223};
qsort(值,5,sizeof(双精度),排序);
对于(n=0;n<5;n++){
printf(“%f”,值[n]);
}
返回(0);
}
除了按降序输出值外,我还想输出它们相应的
索引
。例如,对于给定的
值[]
数组,我将得到[2,0,1,4,3],这表明索引2具有最大值,索引0具有第二大值,依此类推。如何修改上面的代码


谢谢

结构中将值与索引组合,对它们进行排序,并将索引与值一起打印:

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);
}

我建议您阅读更多的内容,尤其是关于比较函数应该返回什么。至于您的问题,您需要第二个包含索引的数组,并且应该对索引数组进行排序。然后,这是最难的部分,您需要找到一种方法将值数组传递给比较函数,比较函数使用索引来检查值数组中的值。@Someprogrammerdude:如果您使用指针数组而不是索引数组,这并不难。使用指针而不是索引通常会简化C编程任务,imho。数组的索引从0开始,增加1到长度减1。降序意味着扭转这种局面。还是说价值观?这是直截了当的。作为旁注:尽管名称不同,
qsort
不需要使用快速排序算法。@你想解释一下你的意思吗?毕竟,该功能在演示中似乎工作得非常好(请参阅底部附近的链接)。@dasblinkenlight非常感谢。这不是按降序排列的吗?我试着翻转标志,但没有work@Medoo这是现在固定的,随着演示。谢谢你指出这一点!
2: 100.130000
0: 88.540000
1: 56.650000
4: 25.223000
3: 2.091000