Skip to content

Commit 5689795

Browse files
authored
added selection sort algorithm (DhanushNehru#167)
1 parent 564ad2a commit 5689795

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Sorting/selectionsort.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Intuition is to pick smallest element every times loop proceeds
3+
"""
4+
5+
def selectionSort(arr):
6+
"""
7+
The selectionSort function implements the selection sort algorithm to sort an array in ascending
8+
order.
9+
10+
:param arr: The parameter `arr` is a list of elements that you want to sort using the selection sort
11+
algorithm
12+
13+
Time complexity: O(N^2), (where N = size of the array), for the best, worst, and average cases.
14+
Space Complexity: O(1)
15+
"""
16+
n = len(arr)
17+
18+
for i in range(0,n-1):
19+
min_idx = i
20+
for j in range(i,n):
21+
if arr[j] < arr[min_idx]:
22+
min_idx = j
23+
# at this point we have collected information which element is smallest (between i and n-1)and its index is stored in min_idx
24+
arr[i], arr[min_idx] = arr[min_idx], arr[i]
25+
26+
27+
temp = input("Enter numbers separated by a comma:\n").strip()
28+
arr = [int(item) for item in temp.split(",")]
29+
selectionSort(arr)
30+
print(arr)

0 commit comments

Comments
 (0)