given an array of integers in random order you have to find the minimum number of swaps to convert it to cyclic sorted array

前端 未结 4 598
野趣味
野趣味 2021-02-06 04:16

if an array is given in random order , you have to output the minimum number of swaps required to convert into cyclic sorted array.

e.g. array given is 3 5 4 2 1

4条回答
  •  太阳男子
    2021-02-06 04:47

    def number_of_swaps(A):
        l=len(A)
        if l < 2:
            return 0
        S1={x:i for i,x in enumerate(A)}
        pos_of_0=S1[0]
        pos_of_N=S1[l-1]
        if pos_of_0 > 0:
            if pos_of_N != (l-1):
                if pos_of_N < pos_of_0:
                    n=(pos_of_0+(l-1)-pos_of_N-1)
                else:
                        n=(pos_of_0+(l-1)-pos_of_N)
            else:
                n=(pos_of_0)
        else :
            n=(l-pos_of_N-1)
        A.remove(0)
        A.remove(l-1)
        B=[x-1 for x in A ]
        return n+number_of_swaps(B)
    
    def min_number_of_swaps(A):
        B=sorted(A)
        swaps=[]
        for i in range(len(A)):
            if i == 0:
                C=B
            else:
                C=B[-i:]+B[0:len(A)-i]
    
            S = {x:i for i,x in enumerate(C)}
            D=[S[i] for i in A]
            swaps.append(number_of_swaps(D))
        return min(swaps)
    

    print min_number_of_swaps([8,5,7,1,2,4,3,6])

    7

    Above code isrecursive approach to solve the problem Complexity O(N^3)

    code has been edited to print only min number of swaps.

提交回复
热议问题