Sunday, 7 July 2019

How to find minimum no of swaps required to sort a list?

The task:

Return the minimum number of swaps to sort the given array/list.

  • Given array 4,3,1,2
  • After swapping we get 1,3,4,2
  • After swapping we get 1,2,4,3
  • After swapping we get 1,2,3,4
  • So, we need a minimum of 3 swaps to sort the array in ascending order.

I came up with 2 solutions, but the 1st solution isn't working and 2nd solution is working fine. Why?

Solution 1

def minimumSwaps(arr):
    swaps = 0
    for i in range(len(arr)):
        if arr[i] != i + 1:
            temp = arr.index(i + 1)
            arr[i], arr[temp] = arr[temp], arr[i]
            swaps += 1
    return swaps

Solution 2

def minimumSwaps(arr):
    n = len(arr)
    arrpos = [*enumerate(arr)]
    arrpos.sort(key=lambda it: it[1])
    vis = {k: False for k in range(n)}
    ans = 0
    for i in range(n):
        if vis[i] or arrpos[i][0] == i:
            continue
        cycle_size = 0
        j = i
        while not vis[j]:
            vis[j] = True
            j = arrpos[j][0]
            cycle_size += 1
        if cycle_size > 0:
            ans += (cycle_size - 1)
    return ans



from How to find minimum no of swaps required to sort a list?

No comments:

Post a Comment