Assume that I have a array_dist
, and I sorted this array in ascending order successfully. But I need also to store the indices of the original array in new array called index_arr
.
Example: array [5,4,3,2,1]
has indices [0,1,2,3,4]
. what I need after sorting the array [1,2,3,4,5]
. is these indices [4,3,2,1,0]
I try the following code which correctly sorted the array_dist
but not correctly store the indices in index_arr
int index_arr[4344]{};
for (int i = 0; i < 4344; ++i) {
index_arr[i] = i;
}
float temp; int x;
for (int i = 0; i < 4344 ; i++)
{
for (int j = i + 1; j < 4344; j++)
{
if (array_dist[i] > array_dist[j])
{
temp = array_dist[i];
array_dist[i] = array_dist[j];
array_dist[j] = temp;
x = index_arr[i];
index_arr[i] = index_arr[j];
index_arr[j] = x;
}
}
}
cout << "print out distance colum after ascending sorting : \n";
for (int i = 0; i < 4344; ++i)
{
cout << index_arr[i] << " : "
<< array_dist[i] << endl;
}
The correctly working code that I compare my results with:
auto sortRuleLambda = [](pair<int, float> const& s1, pair<int, float> const& s2) -> bool
{
return s1.second < s2.second;
};
sort(array_dist.begin(), array_dist.end(), sortRuleLambda);
cout << "print out distance colum after ascending sorting : \n";
for (int i = 0; i < array_X_train.size(); ++i)
{
cout << array_dist[i].first << ": "
<< array_dist[i].second << endl;
}