Skip to content

Commit 48d55b2

Browse files
authored
Merge pull request #17 from marat-s/16_improving_useability_of_selection_sort
[16] Changed manual input to the same style as the rest of the repo.
2 parents bf5db29 + 4f46060 commit 48d55b2

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

Selection_Sort.py

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#Selection Sort
1+
# Selection Sort
22
'''
33
Inside the function create a loop with a loop variable i that counts from 0 to the length of the list – 1.
44
Create a variable smallest with initial value i.
@@ -10,17 +10,28 @@
1010
'''
1111

1212

13+
def selection_sort(alist):
14+
"""
15+
Sorts a given list using a selection sort algorithm
16+
:param alist: a list to be sorted
17+
:return: None
18+
"""
1319

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
20+
for i in range(0, len(alist) - 1): # loop for number of elements in alist
21+
smallest = i # smallest holds the value of i
1722
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
23+
if alist[j] < alist[smallest]: # comparing if value at index j is smaller
24+
smallest = j # then insert value of j in smallest(so we will get smallest value in this)
25+
alist[i], alist[smallest] = alist[smallest], alist[i] # swapping value of smallest and i
26+
27+
28+
if __name__ == '__main__':
29+
30+
arr = [1, 12, 11, -2, 13, 0, 6, 7]
31+
print ('Given array is', end='\n')
32+
print(*arr)
33+
34+
selection_sort(arr)
35+
36+
print('Sorted array is:', end='\n')
37+
print(*arr)

0 commit comments

Comments
 (0)