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

3 篇文章 0 订阅
2 篇文章 0 订阅
快速排序是一种分治策略的算法,通过选取基准值并进行分区操作,将数组分为小于和大于基准值的两部分,然后递归地对这两部分进行排序。在最好的情况下,时间复杂度为O(nlogn),平均情况也为O(n log(n)),最坏情况为O(n^2),空间复杂度为O(1)。
摘要由CSDN通过智能技术生成

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值