Advertisement
karlakmkj

Insertion sort

Jan 7th, 2021
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. def sort_with_select(a_list):
  2.    
  3.     for i in range(len(a_list)):
  4.         minIndex = i
  5.         for j in range(i + 1, len(a_list)):
  6.             #my answer - did the same way as bubble sort
  7.             '''
  8.            if a_list[j] < a_list[i]:
  9.                temp = a_list[i]
  10.                a_list[i] = a_list[j]
  11.                a_list[j] = temp
  12.            '''
  13. #Model answer
  14. #The loops above already take care of the overall control flow of selection sort: all we need to do here is see if the current item is lower than the lowest-found item on the current iteration. So, we check the current item against the lowest-found item so far:
  15.             if a_list[j] < a_list[minIndex]:            
  16.                 #And if it's lower, we note that this is the new lowest-found item:
  17.                 minIndex = j
  18.  
  19.         minValue = a_list[minIndex]  #the smaller no. is j, so assign this as the minValue
  20.         del a_list[minIndex]    #remove the smaller no. value and insert it to the i position
  21.         a_list.insert(i, minValue)
  22.     return a_list
  23.  
  24. print(sort_with_select([5, 3, 1, 2, 4]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement