[英]QuickSort in Python. Increment in array trouble
I am trying to implement quicksort in python. 我正在尝试在python中实现quicksort。 Problem is how to increment/decrement value of i/j in array a
. 问题是如何递增/递减数组a
的i / j值。 I know that I should write i=i+1
and there are no such thing like i++
in python, but I don't understand in which way I should do this. 我知道我应该写i=i+1
并且在python中没有像i++
这样的东西,但是我不知道我应该用哪种方式来做到这一点。 I am newbie, here is my code. 我是新手,这是我的代码。
def quicksort(a,lo,hi):
if(hi<=lo):
return
i = lo - 1
j = hi
v = a[hi]
while True:
while(a[++i] < v):
pass
while(v < a[--j]):
if(j==lo):
break
if(i>=j):
break
t = a[i]
a[i] = a[j]
a[j] = t
t = a[i]
a[i] = a[hi]
a[hi] = t
quicksort(a, lo, i - 1)
quicksort(a, i + 1, hi)
in python, you cannot assign and get the value, that's an intentional limitation to avoid issues with typos, find the proper sequence point... 在python中,您无法分配和获取值,这是有意的限制,以避免拼写错误,找到正确的序列点...
You have no choice than to "emulate" the C-ported code: 您别无选择,只能“模拟” C端口代码:
while(a[++i] < v):
pass
while(v < a[--j]):
if(j==lo):
break
(note that both constructs generate an infinite loop because: (请注意,这两种构造都会产生无限循环,因为:
++i == i
and 和
--j == j
(applying unary plus any number of times or unary minus an even number of times gives the same number, see Why Don't Two Plus Operators Throw an Error (eg, 1 + + 2) ) (应用一元加任意次数或一元减偶数会得到相同的数字,请参阅为什么两个加号运算符不会引发错误(例如1 + + 2) )
So change to: 因此更改为:
i += 1
while(a[i] < v):
i += 1
j -= 1
while(v < a[j]):
if(j==lo):
break
j -= 1
The following construct does not work the same way in Python as it does in C++: 以下构造在Python中的工作方式与在C ++中不同:
while(a[++i] < v):
as well as this one: 以及这个:
while(v < a[--j]):
The way you change the code is the following: 更改代码的方式如下:
def quicksort(a,lo,hi):
if(hi<=lo):
return
i = lo - 1
j = hi
v = a[hi]
while True:
i += 1
while(a[i] < v):
i += 1
pass
j -= 1
while(v < a[j]):
j -= 1
if(j==lo):
break
if(i>=j):
break
t = a[i]
a[i] = a[j]
a[j] = t
t = a[i]
a[i] = a[hi]
a[hi] = t
quicksort(a, lo, i - 1)
quicksort(a, i + 1, hi)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.