C - 在跟踪索引的同时对float数组进行排序

lai*_*bug 10 c arrays sorting

我有一个包含3个浮点值的数组:

float norms[3];

norms[0] = 0.4;
norms[1] = 3.2;
norms[2] = 1.7;
Run Code Online (Sandbox Code Playgroud)

我想按降序对此数组进行排序,同时跟踪数组中值的原始索引.

换句话说,给定norms[] = {0.4, 3.2, 1.7}具有相应索引的数组{0, 1, 2},我基本上想要获得一个对应的数组,该数组ints反映了按降序排序的float值的原始位置norms[].在这种情况下,它会{1, 2, 0}.

实现这一目标的最佳/最干净的方法是什么?

Gau*_*gal 9

使用结构存储值和索引,然后根据值进行排序.

struct str
{
    float value;
    int index;
};

int cmp(const void *a, const void *b)
{
    struct str *a1 = (struct str *)a;
    struct str *a2 = (struct str *)b;
    if ((*a1).value > (*a2).value)
        return -1;
    else if ((*a1).value < (*a2).value)
        return 1;
    else
        return 0;
}

int main()
{
    float arr[3] = {0.4, 3.12, 1.7};
    struct str objects[3];
    for (int i = 0; i < 3; i++)
    {
        objects[i].value = arr[i];
        objects[i].index = i;
    }
    //sort objects array according to value maybe using qsort
    qsort(objects, 3, sizeof(objects[0]), cmp);
    for (int i = 0; i < 3; i++)
        printf("%d ", objects[i].index); //will give 1 2 0
    // your code goes here
    return 0;
}

Run Code Online (Sandbox Code Playgroud)