2026-01-29 08:06:31 +01:00
|
|
|
|
|
|
|
|
"def quicksort(arr):
|
|
|
|
|
"""
|
|
|
|
|
Sorts an array using the Quicksort algorithm.
|
|
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
|
arr (list): The list of elements to be sorted.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
list: The sorted list.
|
|
|
|
|
"""
|
2026-01-29 06:57:52 +01:00
|
|
|
if len(arr) <= 1:
|
|
|
|
|
return arr
|
2026-01-29 08:06:31 +01:00
|
|
|
else:
|
|
|
|
|
# Choose the last element as the pivot
|
|
|
|
|
pivot = arr[-1]
|
|
|
|
|
less = []
|
|
|
|
|
greater = []
|
|
|
|
|
for element in arr[:-1]:
|
|
|
|
|
if element <= pivot:
|
|
|
|
|
less.append(element)
|
|
|
|
|
else:
|
|
|
|
|
greater.append(element)
|
|
|
|
|
# Recursively apply quicksort to sub-arrays
|
|
|
|
|
sorted_less = quicksort(less)
|
|
|
|
|
sorted_greater = quicksort(greater)
|
|
|
|
|
# Combine the sorted sub-arrays and pivot
|
|
|
|
|
return sorted_less + [pivot] + sorted_greater
|
2026-01-29 06:54:10 +01:00
|
|
|
|
2026-01-29 08:06:31 +01:00
|
|
|
# Example usage:
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
sample_array = [3, 6, 8, 10, 1, 2, 1]
|
|
|
|
|
sorted_array = quicksort(sample_array)
|
|
|
|
|
print("Sorted array:", sorted_array)"
|