[Algorithm] Quick Sort - 快速排序Python代码实现

Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are:

  1. Pick an element, called a pivot, from the array.
  2. Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

快排的核心在于分治 (Divide and conquer) 和(原地)分区 (Partition),先在数组中选择一个数字 (基准值 pivot),把数组中的数字分为两部分,比 pivot 小的数字移到数组左边,比 pivot 大的数字移到数组的右边。

Time Complexity: best O(nlogn), average O(n log(n)), worst O(n^2)
Space Complexity: O(1)

def quick_sort(arr):
    arr = quick_sort_recur(arr, 0, len(arr) - 1)
    return arr


def quick_sort_recur(arr, first, last):
    if first < last:
        pivot = partition(arr, first, last)
        quick_sort_recur(arr, first, pivot - 1)
        quick_sort_recur(arr, pivot + 1, last)
    return arr


def partition(arr, first, last):
    wall = first
    for pos in range(first, last):
        if arr[pos] < arr[last]:  # last is the pivot
            arr[pos], arr[wall] = arr[wall], arr[pos]
            wall += 1
    arr[wall], arr[last] = arr[last], arr[wall]
    return wall

猜你喜欢

转载自blog.csdn.net/Treasure99/article/details/91394992