-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathminimum-swaps-2.py
More file actions
34 lines (28 loc) · 867 Bytes
/
minimum-swaps-2.py
File metadata and controls
34 lines (28 loc) · 867 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/bin/python3
import math
import os
import random
import re
import sys
def minimumSwaps(arr):
swaps = 0
index = 0
while index < len(arr):
element = arr[index]
if (index == element - 1):
# This element is in the correct sorted position.
index += 1
else:
# Move the element to the correct sorted position.
# Do not increment index as an unsorted element could have been
# swapped to the current index, therefore re-run this body.
arr[element - 1], arr[index] = arr[index], arr[element - 1]
swaps += 1
return swaps
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()