The minimum number of “insertions” to sort an array

前端 未结 2 1644
我寻月下人不归
我寻月下人不归 2021-01-13 18:28

Suppose there is an unordered list. The only operation we can do is to move an element and insert it back to any place. How many moves does it take to sort the whole list?

相关标签:
2条回答
  • 2021-01-13 18:51

    First note that moving an element doesn't change relative order of elements other than the one being moved.

    Consider the longest non-decreasing subsequence (closely related to the longest increasing subsequence - the way to find them are similar).

    By only moving the element not in this sequence, it's easy to see that we'd end up with a sorted list, since all the elements in this sequence are already sorted relative to each other.

    If we don't move any elements in this sequence, any other element between two elements in this subsequence is guaranteed to be either greater than the larger element, or smaller than the smaller one (if this is not true, it itself would be in the longest sequence), so it needs to be moved.
    (see below for example)

    Does it need to be non-decreasing? Yes. Consider if two consecutive elements in this sequence are decreasing. In this case it would be impossible to sort the list without moving those two elements.

    To minimize the number of moves required, it's sufficient to pick the longest sequence possible, as done above.

    So the total number of moves required is the size of the list minus the size of the longest non-decreasing subsequence.

    An example explaining the value of an element not in the non-decreasing subsequence mentioned above:

    Consider the longest non-decreasing subsequence 1 x x 2 x x 2 x 4 (the x's are some elements not part of the sequence).

    Now consider the possible values for an x between 2 and 4.

    If it's 2, 3 or 4, the longest subsequence would include that element. If it's greater than 4 or smaller than 2, it needs to be moved.

    0 讨论(0)
  • 2021-01-13 18:58

    It is easy to prove that size of the list - size of longest ordered sequence is enough always to sort any sequence, e.g. with mathematical induction.

    You can also easily prove that for some unordered sequences, it is the best what you can do by simply finding such trivial sequence. E.g. to sort the sequence 3, 1, 2 you need one move of one item (3) and it's trivial to see that it cannot be made faster, and obviously size of the list - size of longest ordered sequence is equal to 1.

    However, proving that it is the best for all sequences is impossible because that statement is not actually true: A counter example is a sequence with multiple sorted sub-sequences S[i], where max(S[i]) < min(S[i+1]) for every i. For example see the sequence 1, 2, 3, 1000, 4, 5, 6.

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