Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. import unittest
  2.  
  3. # insertion sort implementation
  4. # time complexity: O(n^2)
  5. # space complexity: O(1)
  6. def insertion_sort(arr):
  7. if not arr or len(arr) <= 1:
  8. return arr
  9. for i in range(len(arr)):
  10. var = arr[i]
  11. j = i
  12. while j > 0 and arr[j-1] > var:
  13. arr[j] = arr[j-1]
  14. j -= 1
  15. arr[j] = var
  16. print("inserting ", var, " at position", j, " in arr ", arr)
  17. return arr
  18.  
  19. class Test(unittest.TestCase):
  20.  
  21. def test_insertion_sort(self):
  22. input = [4, 1, 5, 1, 7, 0, 9, 2]
  23. output = insertion_sort(input)
  24. expected = [0, 1, 1, 2, 4, 5, 7, 9]
  25. self.assertEqual(expected, output)
  26.  
  27. unittest.main(verbosity=2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement