2019-04-30 13:16:42 +00:00
|
|
|
"""
|
|
|
|
Picks the random index as the pivot
|
|
|
|
"""
|
|
|
|
import random
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def partition(a, left_index, right_index):
|
|
|
|
pivot = a[left_index]
|
2019-04-30 13:16:42 +00:00
|
|
|
i = left_index + 1
|
|
|
|
for j in range(left_index + 1, right_index):
|
2022-10-12 22:54:20 +00:00
|
|
|
if a[j] < pivot:
|
|
|
|
a[j], a[i] = a[i], a[j]
|
2019-04-30 13:16:42 +00:00
|
|
|
i += 1
|
2022-10-12 22:54:20 +00:00
|
|
|
a[left_index], a[i - 1] = a[i - 1], a[left_index]
|
2019-04-30 13:16:42 +00:00
|
|
|
return i - 1
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def quick_sort_random(a, left, right):
|
2019-04-30 13:16:42 +00:00
|
|
|
if left < right:
|
|
|
|
pivot = random.randint(left, right - 1)
|
2022-10-12 22:54:20 +00:00
|
|
|
a[pivot], a[left] = (
|
|
|
|
a[left],
|
|
|
|
a[pivot],
|
2019-10-05 05:14:13 +00:00
|
|
|
) # switches the pivot with the left most bound
|
2022-10-12 22:54:20 +00:00
|
|
|
pivot_index = partition(a, left, right)
|
2019-10-05 05:14:13 +00:00
|
|
|
quick_sort_random(
|
2022-10-12 22:54:20 +00:00
|
|
|
a, left, pivot_index
|
2019-10-05 05:14:13 +00:00
|
|
|
) # recursive quicksort to the left of the pivot point
|
|
|
|
quick_sort_random(
|
2022-10-12 22:54:20 +00:00
|
|
|
a, pivot_index + 1, right
|
2019-10-05 05:14:13 +00:00
|
|
|
) # recursive quicksort to the right of the pivot point
|
|
|
|
|
2019-04-30 13:16:42 +00:00
|
|
|
|
|
|
|
def main():
|
2019-10-05 05:14:13 +00:00
|
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
|
|
arr = [int(item) for item in user_input.split(",")]
|
2019-04-30 13:16:42 +00:00
|
|
|
|
|
|
|
quick_sort_random(arr, 0, len(arr))
|
|
|
|
|
|
|
|
print(arr)
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-04-30 13:16:42 +00:00
|
|
|
if __name__ == "__main__":
|
2019-10-05 05:14:13 +00:00
|
|
|
main()
|