Skip to content

Commit 8455aba

Browse files
committed
add Python code for Selection sort
1 parent 0fa29ab commit 8455aba

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def selection_sort(array):
2+
"""
3+
Selection sort sorts an array by placing the minimum element element
4+
at the beginning of an unsorted array.
5+
:param array A given array
6+
:return the given array sorted
7+
"""
8+
9+
length = len(array)
10+
11+
for i in range(0, length):
12+
min_index = i # Suppose that the first (current) element is the minimum of the unsorted array
13+
14+
for j in range(i+1, length):
15+
# Update min_index when a smaller minimum is found
16+
if array[j] < array[min_index]:
17+
min_index = j
18+
19+
if min_index != i:
20+
# Swap the minimum and the initial minimum positions
21+
array[min_index], array[i] = array[i], array[min_index]
22+
23+
return array
24+
25+
# Example:
26+
if __name__ == '__main__':
27+
example_array = [5, 6, 7, 8, 1, 2, 12, 14]
28+
print(example_array)
29+
print(selection_sort(example_array))

0 commit comments

Comments
 (0)