1
- #Selection Sort
1
+ # Selection Sort
2
2
'''
3
3
Inside the function create a loop with a loop variable i that counts from 0 to the length of the list – 1.
4
4
Create a variable smallest with initial value i.
10
10
'''
11
11
12
12
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
+ """
13
19
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
17
22
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