Is there an algorithm better than O(n^2) for re-ordering List 2 to match List 1
List 1 : A B C D
List 2 : B D C A
note: List 2 can have more, less or even completely different items compared to List 1.
Is there an algorithm better than O(n^2) for re-ordering List 2 to match List 1
List 1 : A B C D
List 2 : B D C A
note: List 2 can have more, less or even completely different items compared to List 1.
If you can create a total-ordering for the type of items in the lists, then you can create an index for list 1 by sorting the items. You can then use this index to re-order list 2. This algorithm is O(n log n) in time, and requires an extra O(n) in space.
One possibility that would result in O(n Log(n)) would be the following. This requires reading the list values into an array/vector/sortable type of structure:
After the edit, you mention that the second list may have no correlation to the first list. So the comparison function would have to take that into account. If one or both values being compared are not in the first list, then the compare function needs to make a decision on ordering the values (e.g., do they go at the end or the beginning?).