I was wondering what would be the fastest way to sort an array of objects in the same order as a different array.
Here is an example in C#:
class MyClass { public MyClass(int value) { this.value = value; } int value; public int Value { get { return value; } set { this.value = value; } } } static List<int> sortedValuesList; static List<MyClass> objectList;
What is the fastest way of sorting objectList in the same order as sortedValuesList? There might be multiple objects with the same value.
I already have simple algorithm that can do it, but it’s O(n^2) and requires extra memory.
EDIT: I guess it’s not clear what I’m trying to do. Let’s say a user sees a data grid of salespeople on the screen. He can sort them by any column he wants. Now the user clicks on a button and a table of customers is being shown. Every customer references one of the salespeople. I want to sort the customer list, based on the order of salespeople in previous data grid.
It’s only a theoretical question as I don’t need more performance. I was just wondering if there is some nice sorting algorithm when you need to use a lookup table to compare objects.
Break it into steps:
Total algorithm, O(n log n).
Alternatively, if you don’t want to have the scratch field, you can look up the sort key via the map each time for an overall O(n (log n)^2)