Reputation: 177
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?
Upvotes: 11
Views: 11600
Reputation: 7542
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;
}
Upvotes: 11
Reputation: 2553
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
.
Upvotes: 4
Reputation: 1819
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);
Upvotes: 4