Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
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.

103 lines
2.4 KiB

  1. # Insertion Sort
  2. # Heap Sort
  3. # Merge Sort
  4. #Quick Sort
  5. ## Memory Greedy Solution
  6. ```
  7. def quickSortNormal(data):
  8. """
  9. This is the traditional implementation of quick sort
  10. where there are two recursive calls.
  11. """
  12. if len(data) == 0:
  13. return []
  14. else:
  15. less, equal, greater = partition(data)
  16. return quickSortNormal(less) + equal + quickSortNormal(greater)
  17. ```
  18. ## Accumulation Solution
  19. ```
  20. def quick_sort_accumulation(data, a):
  21. """
  22. Implementation of quickSort which forces tail recursion
  23. by wrapping the second recursive in the tail positioned
  24. recursive call and added an accumulation variable.
  25. """
  26. if len(data) == 0:
  27. return a
  28. less, equal, greater = partition(data)
  29. return quick_sort_accumulation(less,
  30. equal + quick_sort_accumulation(greater, a))
  31. def quicksort(data):
  32. """
  33. Wrapper function for quick sort accumulation.
  34. """
  35. return quick_sort_accumulation(data, [])
  36. ```
  37. ## In-Place Sorting Implementation
  38. ```
  39. def iterative_partition(data, left, right):
  40. """
  41. Function which partitions the data into two segments,
  42. the left which is less than the pivot and the right
  43. which is greater than the pivot. The pivot for this
  44. algo is the right most index. This function returns
  45. the ending index of the pivot.
  46. :param data: array to be sorted
  47. :param left: left most portion of array to look at
  48. :param right: right most portion of the array to look at
  49. """
  50. x = data[right]
  51. i = left - 1
  52. j = left
  53. while j < right:
  54. if data[j] <= x:
  55. i = i + 1
  56. data[i], data[j] = data[j], data[i]
  57. j = j+1
  58. data[i + 1], data[right] = data[right], data[i + 1]
  59. return i + 1
  60. def iterative_quick_sort(data):
  61. """
  62. In place implementation of quick sort
  63. Wrapper function for iterative_quick_sort_helper which
  64. initializes, left, right to be the extrema of the array.
  65. """
  66. iterative_quick_sort_helper(data, 0, len(data) -1)
  67. return data
  68. def iterative_quick_sort_helper(data, left, right):
  69. """
  70. Uses the divide and conquer algo to sort an array
  71. :param data: array of data
  72. :param left: left index bound for sorting
  73. :param right: right bound for sorting
  74. """
  75. if left < right:
  76. pivot = iterative_partition(data, left, right)
  77. iterative_quick_sort_helper(data, left, pivot -1)
  78. iterative_quick_sort_helper(data, pivot+1, right)
  79. ```