python快速递归的方法_快速排序python递归

博客讨论了在实现快速排序过程中遇到的递归调用问题,主要问题在于分区函数后的列表范围改变。解决方案包括调整分区函数的实现,确保枢轴元素正确归位,并修正递归调用的条件,以避免不必要的递归。修复后的代码能够正确执行快速排序算法。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

This is my quick sort code, the partition function works well, but I got a problem while calling the recursion. The pos changes every time it starts the function and then the list limits are change as well. How to fix that?

def partition(lst, start, end):

pos=0

if len(lst)<2:

return

for i in range(len(lst[start:end])):

if lst[i] < lst[end]:

lst[i],lst[pos]=lst[pos],lst[i]

pos+=1

elif i==(len(lst[start:end])-1):

lst[end],lst[pos]=lst[pos],lst[end]

return pos

def quick_sort_recursive(lst, start, end):

pos=partition(lst, start, end)

if start<=pos<=end :

quick_sort_recursive(lst, start, pos-1)

quick_sort_recursive(lst, pos+1, end)

else:

return lst

解决方案

There are numerous problems in your code, here are some fixes just to make it work:

def partition(lst, start, end):

pos = start # condition was obsolete, loop won't

# simply run for empty range

for i in range(start, end): # i must be between start and end-1

if lst[i] < lst[end]: # in your version it always goes from 0

lst[i],lst[pos] = lst[pos],lst[i]

pos += 1

lst[pos],lst[end] = lst[end],lst[pos] # you forgot to put the pivot

# back in its place

return pos

def quick_sort_recursive(lst, start, end):

if start < end: # this is enough to end recursion

pos = partition(lst, start, end)

quick_sort_recursive(lst, start, pos - 1)

quick_sort_recursive(lst, pos + 1, end)

# you don't need to return the list

# it's modified in place

Example:

example = [3,45,1,2,34]

quick_sort_recursive(example, 0, len(example) - 1)

print example

Gives:

python test.py

[1, 2, 3, 34, 45]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值