C - Sort float array while keeping track of indices

Use a structure to store the value as well as index and then sort according to value.

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


The cleanest way i can think of is to create a structure which contains both float and index.

typedef struct str {
float val;
int index;
} str;

then create an array of this structure and sort it according to val.


Just use any sorting algorithm 'aliasing' the original array access. Example with bubblesort

int len = 3;
bool switched = false;

float myFloatArr[3];
int myFloatIndex[3] = {0, 1, 2};

do
{
    switched = false;
    for(i = 1; i < len; i++)
    {
        if(myFloatArr[myFloatIndex[i - 1]] < myFloatArr[myFloatIndex[i]])
        {
            int temp = myFloatIndex[i];
            myFloatIndex[i] = myFloatIndex[i - 1];
            myFloatIndex[i - 1] = temp;
            switched = true;
        }
    }
}
while(switched);

Tags:

C

Arrays

Sorting