Hackerrank-Interview Preparation Kit-Arrays-Minimum Swaps to sort an array

You are given an unordered array consisting of consecutive integers  [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.

This can be easily done by visualizing the problem as a graph. We will have n nodes and an edge directed from node i to node j if the element at i’th index must be present at j’th index in the sorted array.

a

b

def minimumSwaps(arr): 
    n = len(arr) 
    vis = {k:False for k in range(n)} 
    count=0

    for i in range(n):
        cycle_size = 0
        if arr[i] != i+1: 
            start=i
            while not vis[start]:
                vis[start]=True
                start=arr[start]-1
                cycle_size +=1
            if cycle_size >0:
                count+=(cycle_size - 1) 
    return count 

arr=[7,1,3,2,4,5,6]
minimumSwaps(arr)

 

Published 128 original articles · won praise 90 · views 4853

Guess you like

Origin blog.csdn.net/weixin_45405128/article/details/103995533