简体   繁体   中英

How to find the minimum number of moves to sort a list?

In a given list A of N distinct integer numbers, I would like to find the minimum number of moves required to sort the list by moving an element to the end of the list in ascending order.

output is:1 4 3 2 5 [1, 3, 2, 5, 4] 1 [1, 2, 5, 4, 3] 2 [1, 2, 4, 3, 5] 3 [1, 2, 3, 5, 4] 4 [1, 2, 3, 4, 5] 5 None

def end_sort(a,c):
    for i in range(len(a)):
        if(a[i]>a[i+1]):
            a.append(a.pop(i))
            c+=1 
            print(a,c)
            break
    if(a!=sorted(a)):
        end_sort(a,c)
    else:
        return c 
a=list(map(int,input().split(" ")))
c=0
co=end_sort(a,c)
print(co,end="") 

Let's first observe the following facts.

  1. To get the minimum number of steps, a number can only be moved once;
  2. Smaller numbers must be moved first to end up on the left;
  3. A number is out of place if it has a smaller number on its right.

With that in mind we can traverse the list from right to left and keep track of the numbers which are non-decreasing (3) . By sorting those numbers (2) , we get the optimal steps. This is optimal because numbers which have to be moved are moved only once (1) .

def end_sort_steps(lst):
    steps = []
    right_min = max(lst)

    for n in reversed(lst):
        if n >= right_min:
            # Then the number must be moved
            steps.append(n)
        else:
            # Otherwise it is the smallest number seen yet
            right_min = n

    return sorted(steps)

print(end_sort_steps([1, 4, 3, 2, 5])) # [3, 4, 5]
# This corresponds to the steps:
# [1, 4, 3, 2, 5] -> [1, 4, 2, 5, 3] -> [1, 2, 5, 3, 4] -> [1, 2, 3, 4, 5]

Depending on the use you have for this algorithm, all that remains is to put that output into a usable format to represent your sequence of steps.

Alternatively, you can simply keep the step count if that is all that matters.

def end_sort_steps(lst):
    steps = 0
    right_min = max(lst)

    for n in reversed(lst):
        if n >= right_min:
            # Then the number must be moved
            steps += 1
        else:
            # Otherwise it is the smallest number seen yet
            right_min = n

    return steps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM