快速排序python递归

编程入门 行业动态 更新时间:2024-10-27 10:29:38
本文介绍了快速排序python递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的快速排序代码,partition函数运行良好,但是在调用递归时遇到问题. pos每次启动功能时都会更改,然后列表限制也将更改.该如何解决?

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 = [3,45,1,2,34] quick_sort_recursive(example, 0, len(example) - 1) print example

赠予:

python test.py

python test.py

[1、2、3、34、45]

[1, 2, 3, 34, 45]

更多推荐

快速排序python递归

本文发布于:2023-11-28 22:35:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644210.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   快速   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!