Is there a way to restore the original array [5, 8, 1, 9] using the sorted [1, 5, 8, 9]?
Do we have any algorithm for this?
I have tried this
Code: Select all
#include <iostream>
#include <algorithm>
int main()
{
int test[] = { 5,8,1,9 };
int index[] = { 0,1,2,3 };
//...
// perform bubble sort on the data in ascending order
// utilizing the index array as a guide
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 3; ++j)
{
// Note the test with respect to the index
if (test[index[j]] > test[index[j+1]])
// exchange the indices if item is out-of-order
std::swap(index[j], index[j+1]);
}
}
// Output results
std::cout << "sorted: ";
// Print the sorted array
for (int i = 0; i < 4; ++i)
std::cout << test[index[i]] << " ";
// Print the original array
std::cout << "\noriginal: ";
for (int i = 0; i < 4; ++i)
std::cout << test[i] << " ";
}
Code: Select all
sorted: 1 5 8 9
original: 5 8 1 9