Skip to content

Commit 21d008b

Browse files
Merge pull request #6999 from sulaemanahmed/patch-9
Update selection_sort.py
2 parents 34964a6 + 5bacfda commit 21d008b

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

Add Code Here/All_Sorting/selection_sort.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
1-
# Selection sort in Python
2-
# time complexity O(n*n)
3-
#sorting by finding min_index
1+
def selectionSort(array):
2+
size = len(array)
3+
for ind in range(size):
4+
min_index = ind
45

5-
def selectionSort(array, size):
6-
7-
for ind in range(size):
8-
min_index = ind
6+
for j in range(ind + 1, size):
7+
# select the minimum element in every iteration
8+
if array[j] < array[min_index]:
9+
min_index = j
10+
# swapping the elements to sort the array
11+
(array[ind], array[min_index]) = (array[min_index], array[ind])
912

10-
for j in range(ind + 1, size):
11-
# select the minimum element in every iteration
12-
if array[j] < array[min_index]:
13-
min_index = j
14-
# swapping the elements to sort the array
15-
(array[ind], array[min_index]) = (array[min_index], array[ind])
13+
def main():
14+
arr = []
15+
n = int(input("Enter the number of elements: "))
16+
for i in range(n):
17+
element = int(input(f"Enter element {i+1}: "))
18+
arr.append(element)
19+
20+
selectionSort(arr)
21+
print('The array after sorting in Ascending Order by selection sort is:')
22+
print(arr)
23+
24+
if __name__ == "__main__":
25+
main()
1626

17-
arr = [-2, 45, 0, 11, -9,88,-97,-202,747]
18-
size = len(arr)
19-
selectionSort(arr, size)
20-
print('The array after sorting in Ascending Order by selection sort is:')
21-
print(arr)

0 commit comments

Comments
 (0)