Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.5 KiB

  1. """
  2. Jeffery Russell
  3. 10-6-18
  4. File Containing Variations of Quick Sort
  5. """
  6. def partition(data):
  7. """
  8. Partitions a list of data into three sections
  9. which are lower, equal, and equal to the pivot
  10. which is selected to be the last element in the
  11. list.
  12. """
  13. pivot = len(data) -1
  14. lower, equal, upper = [], [], []
  15. for i in range(0, len(data), 1):
  16. if data[i] > data[pivot]:
  17. upper.append(data[i])
  18. elif data[i] == data[pivot]:
  19. equal.append(data[i])
  20. else:
  21. lower.append(data[i])
  22. return lower, equal, upper
  23. def quickSortNormal(data):
  24. """
  25. This is the traditional implementation of quick sort
  26. where there are two recursive calls.
  27. """
  28. if len(data) == 0:
  29. return []
  30. else:
  31. less, equal, greater = partition(data)
  32. return quickSortNormal(less) + equal + quickSortNormal(greater)
  33. def quick_sort_accumulation(data, a):
  34. """
  35. Implementation of quickSort which forces tail recursion
  36. by wrapping the second recursive in the tail positioned
  37. recursive call and added an accumulation variable.
  38. """
  39. if len(data) == 0:
  40. return a
  41. less, equal, greater = partition(data)
  42. return quick_sort_accumulation(less,
  43. equal + quick_sort_accumulation(greater, a))
  44. def quicksort(data):
  45. """
  46. Wrapper function for quick sort accumulation.
  47. """
  48. return quick_sort_accumulation(data, [])
  49. print quicksort([1,3,1,5,7,9,2,3,5,5,6])