Skip to content

Commit 57d36a1

Browse files
committed
Added selection sort
1 parent f3dabfe commit 57d36a1

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

selection_sort.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# The selection sort algorithm sorts an array by repeatedly finding the minimum element.
2+
# Time Complexity : O(n*n)
3+
4+
"""
5+
Algorithm :-
6+
Step 1 − Set MIN to location 0
7+
Step 2 − Search the minimum element in the list
8+
Step 3 − Swap with value at location MIN
9+
Step 4 − Increment MIN to point to next element
10+
Step 5 − Repeat until list is sorted
11+
Pseudocode Selection Sort :-
12+
list : array of items
13+
n : size of list
14+
for i = 1 to n - 1
15+
/* set current element as minimum*/
16+
min = i
17+
18+
/* check the element to be minimum */
19+
for j = i+1 to n
20+
if list[j] < list[min] then
21+
min = j;
22+
end if
23+
end for
24+
/* swap the minimum element with the current element*/
25+
if indexMin != i then
26+
swap list[min] and list[i]
27+
end if
28+
end for
29+
30+
end procedure
31+
"""
32+
33+
34+
def selection_sort(alist):
35+
for i in range(0, len(alist) - 1):
36+
smallest = i
37+
for j in range(i + 1, len(alist)):
38+
if alist[j] < alist[smallest]:
39+
smallest = j
40+
alist[i], alist[smallest] = alist[smallest], alist[i]
41+
42+
43+
# Created a User-Input Array
44+
alist = input('Enter The Numbers : ').split()
45+
alist = [int(x) for x in alist]
46+
selection_sort(alist)
47+
print('Sorted List: ', end='')
48+
print(alist)

0 commit comments

Comments
 (0)