Created
April 21, 2019 06:24
-
-
Save namthatman/f803f8095bf247d65e219733c156190d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
import math | |
import os | |
import random | |
import re | |
import sys | |
# Complete the minimumSwaps function below. | |
def minimumSwaps(arr): | |
minSwap = 0 | |
for i in range(len(arr)): | |
while arr[i] != i+1: | |
temp = arr[i] | |
arr[i] = arr[temp-1] | |
arr[temp-1] = temp | |
minSwap += 1 | |
return minSwap | |
if __name__ == '__main__': | |
fptr = open(os.environ['OUTPUT_PATH'], 'w') | |
n = int(input()) | |
arr = list(map(int, input().rstrip().split())) | |
res = minimumSwaps(arr) | |
fptr.write(str(res) + '\n') | |
fptr.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You are given an unordered array consisting of consecutive integers = [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order. | |
For example, given the array arr = [7,1,3,2,4,5,6] we perform the following steps: | |
i arr swap (indices) | |
0 [7, 1, 3, 2, 4, 5, 6] swap (0,3) | |
1 [2, 1, 3, 7, 4, 5, 6] swap (0,1) | |
2 [1, 2, 3, 7, 4, 5, 6] swap (3,4) | |
3 [1, 2, 3, 4, 7, 5, 6] swap (4,5) | |
4 [1, 2, 3, 4, 5, 7, 6] swap (5,6) | |
5 [1, 2, 3, 4, 5, 6, 7] | |
It took 5 swaps to sort the array. | |
Function Description | |
Complete the function minimumSwaps in the editor below. It must return an integer representing the minimum number of swaps to sort the array. | |
minimumSwaps has the following parameter(s): | |
arr: an unordered array of integers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment