Python Quicksort Algorithm Implementation and Example
Here is a Python implementation of the quicksort algorithm:
def quicksort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = []
right = []
for i in range(1, len(arr)):
if arr[i] < pivot:
left.append(arr[i])
else:
right.append(arr[i])
return quicksort(left) + [pivot] + quicksort(right)
To use this function, simply pass in an array to be sorted:
my_arr = [5, 3, 8, 4, 2, 7, 1, 6]
sorted_arr = quicksort(my_arr)
print(sorted_arr) # [1, 2, 3, 4, 5, 6, 7, 8]
This implementation uses recursion to sort the array, selecting the first element as the pivot and then partitioning the array into two sub-arrays: one containing elements smaller than the pivot, and the other containing elements larger than the pivot. The function then calls itself recursively on each sub-array, concatenating the sorted sub-arrays with the pivot element in between to produce the final sorted array.
原文地址: https://www.cveoy.top/t/topic/nJRN 著作权归作者所有。请勿转载和采集!