Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Sort float array while keeping track of indices

Tags:

arrays

c

sorting

I have an array of 3 floating point values:

float norms[3];

norms[0] = 0.4;
norms[1] = 3.2;
norms[2] = 1.7;

I want to sort this array in descending order while keeping track of the original indexes of the values in the array.

In other words, given the array norms[] = {0.4, 3.2, 1.7} with corresponding indices {0, 1, 2}, I basically want to obtain an array of corresponding ints that reflects the original positions of the float values in norms[] following a descending sort. In this case it would be {1, 2, 0}.

What is the best/cleanest way to achieve this?

like image 804
laideybug Avatar asked Apr 19 '16 09:04

laideybug


People also ask

How do you sort an array by indices?

Approach: Create an array of indices and store 0 to n-1 (n is the size of the given array). Now sort the array by overriding the Comparator in which you will compare the elements of the given array for indices array.

How do you sort an array of floats?

sort(float[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of floats into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.

Can array elements be sorted in descending order?

Array elements can be sorted in descending order by passing in the array and Collections. reverseOrder() as parameters to Arrays. sort(). Note: One thing to keep in mind is that when sorting in descending order, Arrays.


1 Answers

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

like image 122
Gaurav Sehgal Avatar answered Sep 28 '22 09:09

Gaurav Sehgal