-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectionSort.py
29 lines (23 loc) · 935 Bytes
/
SelectionSort.py
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
"""
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
"""
class SelectionSort:
def selection_sort(self, array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
# to sort in descending order, change > to < in this line
# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
array[step], array[min_idx] = array[min_idx], array[step]
return array
if __name__ == "__main__":
data = [-2, 45, 0, 11, -9]
size = len(data)
selection_sort_obj = SelectionSort()
data = selection_sort_obj.selection_sort(data, size)
print('Sorted Array in Ascending Order:')
print(data)