+ 2
Sorting a list.
Though Python has predefined function for sort. I was going through a sorting list function , But couldn't understand the last flow of function. Code being inserted here. Feel free to kindly elaborate flow of this function. https://code.sololearn.com/c50xLL38aS5z/?ref=app I have observed that without if != small: lst [Ā”], lst [small] = lst[small], lst[i] ie without swapping function prints same list without Sorting. How is swapping so much critical in this function?
3 Answers
+ 5
def selection_sort(lst):#define sort function
for i in range(0,len(lst)): loop throug all items in list
small = i #Assume this one (i) is the smallest
for j in range(i+1,len(lst)): Now compare the val in position i with all the items in the rest of the list
if lst[j] < lst[small]:
small = j. # if there are a smaller one, change index of small to this one
if i != small:
lst[i],lst[small] = lst[small] ,lst[i] #Now swop values at asumed smallest with real smallest
def main():
a =[2,18,20,-46]
print(a)
selection_sort(a)
print (a)
main()
+ 5
Think of sorting diferent sized pebbles packed in a row. By swopping the position of the larger ones on the left with smaller ones on the right, ie starting with the left most pebble and continuously swopping it with one that is smaller.you end up with a row of pebbles sorted from small to big.
+ 1
I have observed that without
if != small:
lst [Ā”], lst [small] = lst[small], lst[i]
ie without swapping function prints same list without Sorting. How is swapping so much critical in this function?