quick-sort.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Quick sort
  2. # The idea is to pick a pivot point and sort the array such that
  3. # the left part of the coverging point is smaller than the pivor point,
  4. # the right larger.
  5. # converging point is found when the right pointer is smaller than the left pointer
  6. import pytest
  7. def test_quick_sort():
  8. input1 = [31, 23, 43, 56, 9]
  9. input2 = []
  10. assert quick_sort(input1) == [9, 23, 31, 43, 56]
  11. assert quick_sort(input2) == []
  12. def quick_sort(input):
  13. qs_helper(input, 0, len(input)-1)
  14. return input
  15. def qs_helper(input, start, end):
  16. if start < end:
  17. partition = qs_partition(input, start, end)
  18. # left partition
  19. qs_helper(input, start, partition-1)
  20. # right partition
  21. qs_helper(input, partition+1, end)
  22. def qs_partition(input, start, end):
  23. pivot = input[start]
  24. left = start + 1
  25. right = end
  26. done = False
  27. while not done:
  28. while left <= right and input[left] < pivot:
  29. left += 1
  30. while input[right] > pivot and left <= right:
  31. right -= 1
  32. if left > right: done = True
  33. else:
  34. input[left], input[right] = input[right], input[left]
  35. input[start], input[right] = input[right], input[start]
  36. return right