Guest User

Untitled

a guest
Jul 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. def insertion_sort(input_list: list) -> list:
  2. """Sort a list with insertion sort algorithm.
  3. :param input_list: a list to be sorted.
  4. :type input_list: list
  5. :return: sorted list in ascending order.
  6. :rtype: list
  7. """
  8. # Check if need to sort
  9. if input_list == [] or len(input_list) == 1:
  10. return input_list
  11. else:
  12. # Create a tmporary list to hold middle steps
  13. tmp = []
  14. # Pick one element
  15. for picked_element in input_list:
  16. # Check length
  17. length = len(tmp)
  18. if length == 0:
  19. tmp.append(picked_element)
  20. else:
  21. # Scan tmp list to find position to insert
  22. # Use var inserted to determine if need to append
  23. inserted = False
  24. for potential_position in range(length):
  25. # Right position found
  26. if tmp[potential_position] > picked_element:
  27. tmp.insert(potential_position, picked_element)
  28. inserted = True
  29. break
  30. # All existing elements are smaller, no insertion happends,
  31. # just append at the end
  32. if not inserted:
  33. tmp.append(picked_element)
  34. return tmp
Add Comment
Please, Sign In to add comment