File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments