Skip to content

Commit 8d33da4

Browse files
authored
Update sorting_algorithms.py
Added Selection Sort
1 parent 54892ef commit 8d33da4

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

HackerEarth/sorting_algorithms.py

+41
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,45 @@
3030
swap = True
3131
print(numswaps)
3232

33+
"""
34+
Selection Sort
35+
Time Complexity:
36+
To find the minimum element from the array of N elements, N-1 comparisons are required. After putting the minimum element in its proper
37+
position, the size of an unsorted array reduces to N-1 and then N-2 comparisons are required to find the minimum in the unsorted array.
38+
Therefore (N-1) + (N-2 ) + ....... + 1 = ( N \cdot (N-1) ) / 2 comparisons and N swaps result in the overall complexity of O( N^2 ).
39+
40+
Consider an Array a of size N
41+
Iterate from 1 to N
42+
In i^{th} iteration select the i^{th} minimum and swap it with a[i]
43+
You are given an array a, size of the array N and an integer x. Follow the above algorithm and print the state of the array after
44+
x iterations have been performed.
45+
Input Format
46+
The first line contains two integer N and x denoting the size of the array and the steps of the above algorithm to be performed
47+
respectively. The next line contains N space separated integers denoting the elements of the array.
48+
Output Format
49+
Print N space separated integers denoting the state of the array after x steps
50+
Constraints
51+
1 \le N \le 100
52+
1 \le a[i] \le 100
53+
1 \le x \le N
54+
"""
55+
[size,iterations] = map(int,input().split())
56+
numlist = list(map(int,input().split()))
57+
temp = 0
58+
59+
for x in range(0,size):
60+
if iterations == 0:
61+
break
62+
minimum = x
63+
for y in range(x+1,size):
64+
if numlist[y] < numlist[minimum]:
65+
minimum = y
66+
if minimum != x: #swap
67+
temp = numlist[x]
68+
numlist[x] = numlist[minimum]
69+
numlist[minimum] = temp
70+
iterations -= 1
71+
72+
print(' '.join(list(map(str,numlist))))
73+
3374

0 commit comments

Comments
 (0)