Sorting some numbers...kind of

Started by
14 comments, last by cignox1 12 years, 2 months ago
If you want to output the original indices as well, then that is a different problem from just outputting the values you talked about from the beginning.

Different, but not much so really. Store a copy of the list which contains pairs of original values and indices. Then you can sort the list by the value field, and output both the value and the index.
Advertisement
Yeah, I know. I asked the question in a kind of stupid way.

I think with the current amount of help, I'll be able to make it work :)

Thanks everyone.

What about something like this...
[/quote]
You could get something like that to work for distinct values, but data sets with duplicate values are a bit trickier.

Even if you got such a technique to work, it would be O(n

[sup]2[/sup]). Sorting the list can be done in O(n log n), output can be in O(n), which would mean that the sort then display algorithm would be O(n log n) overall. Of course, if we were talking about the performance we could also talk about the allocation overhead and cache pressure of using a linked list over a contiguous data sequence like a dynamic array.

Sort an array of indices:

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>

class indirect_compare {
std::vector<int> const &v;

public:
indirect_compare(std::vector<int> const &v) : v(v) {
}

bool operator()(int a, int b) {
return v[a] < v;
}
};

int main() {
std::vector<int> values;
std::vector<int> indices;

for (int i=0; i<4; ++i) {
values.push_back(std::rand());
indices.push_back(i);
}

std::sort(indices.begin(), indices.end(), indirect_compare(values));

std::cout << "Original list:\n";
for (int i=0; i<4; ++i)
std::cout << values << '\n';
std::cout << '\n';

std::cout << "After sorting:\n";
for (int i=0; i<4; ++i)
std::cout << values[indices] << " (index " << indices << ")\n";
std::cout << '\n';
}
Thank you for the reply. But I've already solved it happy.png

Edit: Forgot that it might be pointed towards other people.


What about something like this...

You could get something like that to work for distinct values, but data sets with duplicate values are a bit trickier.

Even if you got such a technique to work, it would be O(n

[sup]2[/sup]). Sorting the list can be done in O(n log n), output can be in O(n), which would mean that the sort then display algorithm would be O(n log n) overall. Of course, if we were talking about the performance we could also talk about the allocation overhead and cache pressure of using a linked list over a contiguous data sequence like a dynamic array.
[/quote]

Yes, of course it was not a serious alternative to sorting a list, but an option as the op seemed to dislike any sorting.
Good point with the duplicates, though, I have not thought to that :-)

This topic is closed to new replies.

Advertisement