Python Quicksort: Code & Explanation

Quick sort is a common sorting algorithm where a pivot value is selected, the array is divided into two parts, one part containing values smaller than the pivot and the other containing values larger than the pivot, and then recursively sorting both parts of the array.

Here is a code example of implementing quick sort in Python:

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    else:
        pivot = arr[0]
        less = [x for x in arr[1:] if x <= pivot]
        greater = [x for x in arr[1:] if x > pivot]
        return quick_sort(less) + [pivot] + quick_sort(greater)

# 测试示例
arr = [3, 6, 8, 10, 1, 2, 1]
sorted_arr = quick_sort(arr)
print(sorted_arr)

In this example, we have defined a quick_sort function to implement the quicksort algorithm. It first checks if the length of the array is less than or equal to 1, and if so, returns the array. Otherwise, it selects the first element of the array as the pivot, then uses list comprehension to obtain two subarrays, less and greater, for elements less than or equal to the pivot and elements greater than the pivot, respectively. Finally, it recursively sorts the two subarrays and merges the results.

You can copy and paste the code above into a Python interpreter to run and test the efficiency of the quicksort algorithm.

bannerAds