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?
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With