Skip to content

Commit 3500314

Browse files
authored
Merge pull request #13 from shriyaMadan/patch-2
Created selection sort documentation and script
2 parents 7989164 + 21e55fd commit 3500314

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Selection_Sort.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#Selection Sort
2+
'''
3+
Inside the function create a loop with a loop variable i that counts from 0 to the length of the list – 1.
4+
Create a variable smallest with initial value i.
5+
Create an inner loop with a loop variable j that counts from i + 1 up to the length of the list – 1.
6+
Inside the inner loop, if the elements at index j is smaller than the element at index smallest, then set smallest equal to j.
7+
After the inner loop finishes, swap the elements at indexes i and smallest.
8+
9+
Author: Shriya Madan
10+
'''
11+
12+
13+
14+
def selection_sort(alist): #selection sort function
15+
for i in range(0, len(alist) - 1): #loop for number of elements in alist
16+
smallest = i #smallest holds the value of i
17+
for j in range(i + 1, len(alist)):
18+
if alist[j] < alist[smallest]: #comparing if value at index j is smaller
19+
smallest = j #then insert value of j in smallest(so we will get smallest value in this)
20+
alist[i], alist[smallest] = alist[smallest], alist[i] #swapping value of smallest and i
21+
22+
alist = input('Enter the list of numbers: ').split() #taking user inputs
23+
alist = [int(x) for x in alist]
24+
selection_sort(alist) #elements passed to the function for sorting
25+
print('Sorted list: ', end='')
26+
print(alist) #sorted array is printed

0 commit comments

Comments
 (0)