def minimumSwaps(arr):
    
    positions = {value: index for index, value in enumerate(arr)}

    counter = 0
    last_index = 0
    while True:
        swaps = False
        
        for index in range(last_index, len(arr)):
            value = arr[index]
            if (index + 1) != value:

                real_position = positions[index + 1]

                arr[real_position], arr[index] = arr[index], arr[real_position]
                positions[index + 1], positions[value] = positions[value], positions[index + 1]

                counter += 1
                swaps = True

                last_index = index
                
                break
                
        if not swaps:
            break
    return counter



arr = [4,3,1,2]
result = minimumSwaps(arr)

print(result)

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: