Algorithm: optimal way to rearrange a list from one order to another?

后端 未结 4 1014
旧巷少年郎
旧巷少年郎 2020-12-30 13:30

EDIT: I\'m not sure that my original question is clear enough. I need an algorithm that will compute the minimal sequence of moves to rearrange an array from one ord

相关标签:
4条回答
  • 2020-12-30 14:10

    My first thought is you should use Selection sort instead of the built-in sort method, since it makes the lowest ammount of swaps needed. That way you can just move the DOM element around when moving the id in the list.

    0 讨论(0)
  • 2020-12-30 14:28

    Knuth Volume 3 has a section on "sorting networks". He doesn't go into a lot of detail about how to construct minimum comparison networks, but does cite some work (e.g., by Batcher and himself) about how to construct them. Note that while these are notes as "minimum comparison networks", few (if any) of them has really been proven to be minimal -- they're attempts at minimizing the number of comparators needed, but not necessarily successful in terms of actually achieving the true minimum.

    0 讨论(0)
  • 2020-12-30 14:32

    Split out the keys and the array indexes into a separate array of objects {key, index}. Sort that array (using the best sort you can, of course; either a merge sort if the comparisons are expensive, or quicksort if they're cheap). You now know, from the actual indexes into the sorted array and the index values stored in each element, how to rearrange the original array.

    Once you've sorted the keys, the "optimal" number of moves will be the O(n) of the original array. If you want to rearrange the original array in place, then you can derive the interchanges from your sorted list of indexes pretty simply.

    0 讨论(0)
  • 2020-12-30 14:35

    http://en.wikipedia.org/wiki/Longest_increasing_subsequence

    Find the longest increasing subsequence (according to the new sort order). Then move each element which is not in that sequence, into its place relative to the elements already in the sequence.

    In your example, 'a, b, e' and 'a, c, e' are tied for longest increasing subsequence. The best you can do is choose one of those, and just move the other elements.

    0 讨论(0)
提交回复
热议问题