Program to find how many swaps needed to sort an array in Python

Finding the minimum number of swaps needed to sort an array is a classic problem. We need to consider both ascending and descending order, then return the minimum swaps required.

So, if the input is like nums = [2, 5, 6, 3, 4], then the output will be 2 because initially nums has [2, 5, 6, 3, 4]. If we swap numbers 6 and 4, the array will be [2, 5, 4, 3, 6]. Then, if we swap the numbers 5 and 3, the array will be [2, 3, 4, 5, 6]. So 2 swaps are needed to make the array sorted in ascending order.

Algorithm

To solve this, we will follow these steps −

  • Create a function swap_count() that takes input_arr
  • pos := new list containing tuples (item_position, item) for each item in input_arr
  • Sort the list pos according to the items in input_arr
  • cnt := 0
  • For each index in range 0 to size of input_arr, do:
    • While pos[index][0] is not equal to index:
      • cnt := cnt + 1
      • swap_index := pos[index][0]
      • Swap the values of pos[index] and pos[swap_index]
  • Return minimum of (swap_count(input_arr), swap_count(input_arr in reverse order))

Example

Let us see the following implementation to get better understanding ?

def swap_count(input_arr):
    pos = sorted(list(enumerate(input_arr)), key=lambda x: x[1])
    cnt = 0
    
    for index in range(len(input_arr)):
        while True:
            if pos[index][0] == index:
                break
            else:
                cnt += 1
                swap_index = pos[index][0]
                pos[index], pos[swap_index] = pos[swap_index], pos[index]
    
    return cnt

def solve(input_arr):
    return min(swap_count(input_arr), swap_count(input_arr[::-1]))

nums = [2, 5, 6, 3, 4]
print(solve(nums))

The output of the above code is ?

2

How It Works

The algorithm works by creating position mappings and finding cycles in the permutation. Each cycle requires (cycle_length - 1) swaps to resolve. We calculate swaps for both ascending and descending order, then return the minimum.

Another Example

Let's test with a different array ?

def swap_count(input_arr):
    pos = sorted(list(enumerate(input_arr)), key=lambda x: x[1])
    cnt = 0
    
    for index in range(len(input_arr)):
        while True:
            if pos[index][0] == index:
                break
            else:
                cnt += 1
                swap_index = pos[index][0]
                pos[index], pos[swap_index] = pos[swap_index], pos[index]
    
    return cnt

def solve(input_arr):
    return min(swap_count(input_arr), swap_count(input_arr[::-1]))

# Test with different arrays
test_arrays = [
    [4, 3, 2, 1],
    [1, 5, 4, 3, 2],
    [1, 2, 3, 4, 5]
]

for arr in test_arrays:
    result = solve(arr)
    print(f"Array {arr}: {result} swaps needed")

The output of the above code is ?

Array [4, 3, 2, 1]: 2 swaps needed
Array [1, 5, 4, 3, 2]: 2 swaps needed
Array [1, 2, 3, 4, 5]: 0 swaps needed

Conclusion

This algorithm efficiently finds the minimum swaps by analyzing permutation cycles. The time complexity is O(n log n) due to sorting, and it considers both ascending and descending order to find the optimal solution.

Updated on: 2026-03-26T14:37:34+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements