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

后端 未结 4 1031
旧巷少年郎
旧巷少年郎 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: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.

提交回复
热议问题