Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. # ENCM 335 Fall 2019 Lab 8 Exercise C Part 2
  2.  
  3.  
  4. # Writing code to sort a list is a good for learning Python syntax,
  5. # but if you need to sort a list in a bigger project, please DON'T
  6. # write your own sort function!
  7. #
  8. # If x is a list, this statement will sort it ...
  9. #
  10. # x.sort()
  11. #
  12. # And if y is a list, this statement makes z a sorted copy of y
  13. # and leaves y unchanged ...
  14. #
  15. # z = sorted(y)
  16.  
  17. def insertion_sort(x):
  18.     """Sort list from smallest to largest with insertion sort."""
  19.  
  20.     i = 0
  21.     k = 1
  22.    
  23.     while k < len(x):
  24.         old_val = x[k]
  25.         i = k
  26.         while i !=0 and x[i-1] > old_val:
  27.             x[i] = x[i-1]
  28.             i -= 1
  29.         x[i] = old_val
  30.         k += 1
  31.  
  32. def do_a_test(a):
  33.     print('before sorting:', a)
  34.     insertion_sort(a)
  35.     print('after sorting: ', a)
  36.     print()
  37.  
  38. do_a_test([10, 9, 7, 11, 8, 6, 12])
  39. do_a_test([2.5, -0.5, 1.25, 0.25, -1.5])
  40. do_a_test(['BC', 'AB', 'SK', 'MN', 'ON', 'QC', 'NB', 'PE', 'NS', 'NL'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement