I am trying to calculate the number of minimum swaps while sorting an unordered array with integers.
An example.
Input;
array = [4, 3, 1, 2]
calculate_swaps(array)
Output;
# Initial array = [4, 3, 1, 2]
# 1st iteration = [1, 3, 4, 2]
# 2nd iteration = [1, 2, 4, 3]
# 3rd iteration = [1, 2, 3, 4]
3 # minimum amount of swaps to sort the array.
I have tried "selection sorting algorithm' here below. It works. Since it performs with O(n2) time complexity, my algorithm takes too much time for calculation on big arrays (with size = 50,000).
Here is my code. How can I overcome this performance issue?
def calculate_swaps(arr):
min_swaps = 0
minimum = 0
for i in range(len(arr) - 1):
if (arr[i] == i + 1):
continue
minimum = i
for j in range(i + 1, len(arr)):
# Find the smallest value
if arr[j] < arr[minimum]:
minimum = j
# Swap
if minimum != i:
arr[minimum], arr[i] = arr[i], arr[minimum]
min_swaps += 1
return(min_swaps)