Syntax error Program to find number of swaps required to sort the sequence in python

Program to find number of swaps required to sort the sequence in python



Suppose we have a list of distinct numbers; we have to find the minimum number of swaps required to sort the list in increasing order.

So, if the input is like nums = [3, 1, 7, 5], then the output will be 2, as we can swap 3 and 1, then 5 and 7.

To solve this, we will follow these steps:

  • sort_seq := sort the list nums
  • table := a new map
  • for each index i and value n in nums, do
    • table[n] := i
  • swaps := 0
  • for i in range 0 to size of nums, do
    • n := nums[i]
    • s_n := sort_seq[i]
    • s_i := table[s_n]
    • if s_n is not same as n, then
      • swaps := swaps + 1
      • nums[s_i] := n
      • nums[i] := s_n
      • table[n] := s_i
      • table[s_n] := i
  • return swaps

Let us see the following implementation to get better understanding:

Example Code

Live Demo

class Solution:
def solve(self, nums):
   sort_seq = sorted(nums)
   table = {}

   for i, n in enumerate(nums):
      table[n] = i
   swaps = 0
   for i in range(len(nums)):
      n = nums[i]
      s_n = sort_seq[i]
      s_i = table[s_n]

      if s_n != n:
         swaps += 1
         nums[s_i] = n
         nums[i] = s_n
         table[n] = s_i
         table[s_n] = i

      return swaps

ob = Solution()
nums = [3, 1, 7, 5]
print(ob.solve(nums))

Input

[3, 1, 7, 5]

Output

2
Updated on: 2020-11-25T13:01:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements