[英]QuickSort Code (Python)
this is my first post on StackExchange, and I'm trying to figure out what's wrong with my code for a simple QuickSort program. 这是我在StackExchange上的第一篇文章,我试图找出一个简单的QuickSort程序的代码出了什么问题。 I'm fairly sure that some integer simply needs to be adjusted by +-1 or something, so I'd like to keep the format. 我很确定某些整数只需要用+ -1或其他值进行调整,因此我想保留格式。
The code is as follows: 代码如下:
def QuickSort(Array_1,lower=0,upper=-1):
print(Array_1)
if upper==-1:
upper=len(Array_1)-1
if lower<upper:
Array_2,pivot=partition(Array_1,lower,upper)
Array_3=QuickSort(Array_2,lower,pivot-1)
Array_4=QuickSort(Array_3,pivot+1,upper)
return Array_4
else:
return Array_1
def partition(Array,lower,upper):
key=Array[upper]
print(Array)
i=lower
j=lower-1
z=0
for j in range(lower,upper-1):
print(i)
print(j)
if Array[j]<key:
Array[i],Array[j]=Array[j],Array[i]
i+=1
Array[upper],Array[i]=Array[i],Array[upper]
print(Array)
return (Array,i+1)
Additionally, one thing I noticed is that the code runs infinitely if I change the 'j in range(p,r-1)' to 'j in range(p,r)', but it doesn't look like it should. 另外,我注意到的一件事是,如果我将“范围(p,r-1)中的j更改为范围(p,r)中的j”,则代码将无限运行,但看起来不应该如此。 Thoughts? 思考?
Variables have been edited to meaningful variables. 变量已被编辑为有意义的变量。 I think They were all changed correctly. 我认为它们都已正确更改。
input: [8, 18, 6, 19]
desired output: [6,8,18,19]
output: [19, 8, 18, 6]
input: [16, 0, 20, 10, 5, 2]
desired output: [0,2,5,10,16,20]
output: [2, 0, 20, 16, 10, 5]
There were only small errors in your partition
function as you already guessed: 正如您已经猜到的那样,您的partition
功能中只有一些小错误:
1) Your for
loop was not processing the last element because you used range(lower, upper-1)
instead of range(lower, upper)
1)您的for
循环未处理最后一个元素,因为您使用了range(lower, upper-1)
而不是range(lower, upper-1)
range(lower, upper)
2) You should finally return i
instead of i+1
2)您最终应该返回i
而不是i+1
def partition(Array,lower,upper):
...
for j in range(lower,upper):
...
return (Array,i)
Results: 结果:
>>> print QuickSort([8, 18, 6, 19])
[6, 8, 18, 19]
and 和
>>> print QuickSort([16, 0, 20, 10, 5, 2])
[0, 2, 5, 10, 16, 20]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.