2026-01-29 06:57:52 +01:00
|
|
|
def quicksort(arr):
|
|
|
|
|
"""Recursively sorts an array using the Quicksort algorithm."""
|
|
|
|
|
if len(arr) <= 1:
|
|
|
|
|
return arr
|
|
|
|
|
pivot = arr[len(arr) // 2]
|
|
|
|
|
left = [x for x in arr if x < pivot]
|
|
|
|
|
middle = [x for x in arr if x == pivot]
|
|
|
|
|
right = [x for x in arr if x > pivot]
|
|
|
|
|
return quicksort(left) + middle + quicksort(right)
|
2026-01-29 06:54:10 +01:00
|
|
|
|
2026-01-29 06:57:52 +01:00
|
|
|
|
|
|
|
|
def quicksort_inplace(arr, low=0, high=None):
|
|
|
|
|
"""In-place Quicksort implementation for efficiency."""
|
2026-01-29 06:54:10 +01:00
|
|
|
if high is None:
|
|
|
|
|
high = len(arr) - 1
|
|
|
|
|
if low < high:
|
2026-01-29 06:57:52 +01:00
|
|
|
pivot_index = partition(arr, low, high)
|
|
|
|
|
quicksort_inplace(arr, low, pivot_index - 1)
|
|
|
|
|
quicksort_inplace(arr, pivot_index + 1, high)
|
2026-01-29 06:54:10 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def partition(arr, low, high):
|
|
|
|
|
pivot = arr[high]
|
2026-01-29 06:57:52 +01:00
|
|
|
i = low
|
2026-01-29 06:54:10 +01:00
|
|
|
for j in range(low, high):
|
|
|
|
|
if arr[j] <= pivot:
|
|
|
|
|
arr[i], arr[j] = arr[j], arr[i]
|
2026-01-29 06:57:52 +01:00
|
|
|
i += 1
|
|
|
|
|
arr[i], arr[high] = arr[high], arr[i]
|
|
|
|
|
return i
|