Skip to content

Commit 6deb75b

Browse files
committed
SelectionSort.py
1 parent 7219dfc commit 6deb75b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
Selection Sort
3+
4+
Time Complexity: O(n^2)
5+
"""
6+
7+
def FindMin(arr):
8+
"""finds minimum element from the list"""
9+
min = 100000 # let list contain +ve numbers only: so minimum number is -1
10+
for i in range(len(arr)):
11+
if arr[i] < min:
12+
min = arr[i]
13+
return min
14+
15+
16+
def SelectionSort(arr):
17+
size = len(arr)
18+
for i in range(size-1): # decreased 1 iteration: no need to iterate to the last element
19+
minIndex = i # pointer initialised to ith index for selection sort
20+
for j in range(minIndex+1, size):
21+
if arr[j] < arr[minIndex]: # if current index < minimum index of the array
22+
minIndex = j # minimum index updated
23+
# swapping element
24+
if i != minIndex:
25+
arr[i], arr[minIndex] = arr[minIndex], arr[i]
26+
27+
if __name__ == '__main__':
28+
elements = [100, 19, 28, 14, 6, 1, 99]
29+
print(FindMin(elements)) # prints minimum element from the list
30+
SelectionSort(elements)
31+
print(elements)
32+
33+
# running test cases
34+
35+
tests = [
36+
[89, 78, 61, 23, 21, 53, 12, 1, 2, 6, 3, 17, 9],
37+
[],
38+
[1, 2, 3, 4, 5],
39+
[350, 3, 1, 99, 12, 78, 12, 1200],
40+
[9]
41+
]
42+
# print("Tests case testing...")
43+
for elements in tests:
44+
SelectionSort(elements)
45+
print(elements)

0 commit comments

Comments
 (0)