加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-快速排序

发布时间:2020-12-20 09:50:39 所属栏目:Python 来源:网络整理
导读:核心思想:取一个初始值,将数组中比该值小的放在其左边,比其大的放在右边, 再对左、右子数组进行相同操作,直到数组排好序。 def quicksort(nums): l = 0 r = len(nums) - 1 _quicksort(nums,l,r) _quicksort(nums,r): if l r: p = partition(nums,r) _qu

核心思想:取一个初始值,将数组中比该值小的放在其左边,比其大的放在右边, 再对左、右子数组进行相同操作,直到数组排好序。

def quicksort(nums):
    l = 0
    r = len(nums) - 1
    _quicksort(nums,l,r)
 _quicksort(nums,r):
    if l < r:
        p = partition(nums,r)
        _quicksort(nums,p-1)
        _quicksort(nums,p+1,r):
    base = nums[l]
    j = l+1
    for i in range(l+1,r+1):
        if nums[i]<base:
            nums[i],nums[j]=nums[j],nums[i]
            j+=1
    nums[l],nums[j-1]=nums[j-1],nums[l]
    return j-1

nums = [6,2,5,3,4,8,1,7]
quicksort(nums)
print(nums)

改进:随机选择初始值,避免数组有序使算法退化。从两边开始遍历,减少遍历时间。

import random
 random.randint(l,r)
    nums[l],nums[ind] = nums[ind],nums[l]
    base = nums[l]
    i,j = l+1while True:
        while i <= r and nums[i] < base:  # 不能改为nums[i] <= base          
            i += 1
        while j >= l + 1 and nums[j] > base:   不能改为nums[j] >= base.
            j -= 1
        if i > j:
            break
        else:
            nums[i],nums[j] = nums[j],nums[i]
            i += 1
            j -= 1
    nums[j],nums[l] = nums[l],nums[j]
    return j

nums = [6,1)">print(nums)

改进:三路快排,用于解决数组中有较多重复的值。

 r:
        lt,gt = nums[l]
    lt = l   nums[l+1...lt] < base
    gt = r + 1   nums[gt...r] > base
    i = l + 1   nums[lt+1...i] == base
    while (i < gt):
         i==gt时表示已经比较结束
        if (nums[i] < base):
            nums[i],nums[lt+1] = nums[lt+1
            i += 1
        elif (nums[i] >-= 1
        else:   nums[i] == base
            i += 1 nums[lt],1)"> lt,gt

nums = [6,1)">print(nums)

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读