 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find how many swaps needed to sort an array in Python
Suppose, we have an array called nums and we have to find the number of swaps needed to make nums sorted in any order, either ascending or descending.
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.
To solve this, we will follow these steps −
- Define a function swap_count() . This will take input_arr- pos := new list containing tuples (item_postion, item) for each item in input_arr
- sort the list pos according to the items in input_arr
- cnt := 0
- for index in range 0 to size of input_arr, do- while True, do- if pos[index, 0] is same as index, then- exit from the loop
 
- otherwise,- cnt := swap_count + 1
- swap_index := pos[index, 0]
- swap the values of (pos[index], pos[swap_index])
 
 
- if pos[index, 0] is same as index, then
 
- while True, do
- return cnt
 
- From the main function/method, do the following −- 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))
Input
[2, 5, 6, 3, 4]
Output
2
Advertisements
 