Home > Article > Backend Development > How to implement quick sort using Python
How to implement quick sorting in Python: 1. Define a function called quick_sort and use the recursive method to implement quick sorting; 2. Check the length of the array. If the length is less than or equal to 1, return the array directly. , otherwise, select the first element in the array as the pivot element (pivot), and then divide the array into two sub-arrays smaller than the pivot element and larger than the pivot element; 3. Connect the two sub-arrays and the pivot element to form Just sort the array.
The operating system for this tutorial: Windows 10 system, Python version 3.11.4, Dell G3 computer.
The following is how to implement quick sort using Python:
def quick_sort(arr): if len(arr) <= 1: return arr else: pivot = arr[0] less_than_pivot = [x for x in arr[1:] if x <= pivot] greater_than_pivot = [x for x in arr[1:] if x > pivot] return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot) # 示例 arr = [3, 6, 8, 10, 1, 2, 1] sorted_arr = quick_sort(arr) print(sorted_arr)
In this example, we define a function called quick_sort, which uses a recursive method to implement quick sort. The function first checks the length of the array, and if the length is less than or equal to 1, it returns the array directly. Otherwise, we select the first element in the array as the pivot element, and then split the array into two subarrays smaller than the pivot element and larger than the pivot element. Finally, we concatenate the two subarrays and the pivot element to form a sorted array.
The above is the detailed content of How to implement quick sort using Python. For more information, please follow other related articles on the PHP Chinese website!