[英]Quicksort in place Python
I am extremely new to Python and i am trying my hand in Algorithms. 我是Python的新手,正在尝试算法。 I was just trying my hands in the in place sorting of an array using quicksort algo.
我只是在尝试使用quicksort算法对数组进行原位排序。
Below is my code . 下面是我的代码。 When i run this there is an infinite loop as output.
当我运行它时,有一个无限循环作为输出。 Can anyone kindly go through the code and let me know where i am going wrong logically :
任何人都可以通过这段代码来让我知道我在哪里出错了:
def quicksort(arr,start,end):
if start < end:
pivot = arr[int(start + (end - start)/2)]
while end > start:
while arr[start] < pivot:
start = start + 1
while arr[end] > pivot:
end = end - 1
if start <= end:
arr[start],arr[end] = arr[end],arr[start]
start = start + 1
end = end - 1
quicksort(arr,0,end)
quicksort(arr,start,len(arr) - 1)
else:
return
arr = list(map(int,input().split(" ")))
quicksort(arr,0,len(arr) - 1)
print ("The final sorted array:",arr)
Thanks for any help in advance. 感谢您的任何帮助。
Your recursion is wrong. 您的递归是错误的。 After doing Hoare Partition, you should do :
完成Hoare分区后,您应该执行以下操作:
So you have to create new variables beside the argument to maintain start,end and indices that move toward each other in the partition. 因此,您必须在参数旁边创建新变量,以维持分区中彼此相对移动的开始,结束和索引。
In order to not change a lot of your code, i suggest you to change the argument 为了不更改很多代码,我建议您更改参数
def quicksort(arr,left,right):
start = left
end = right
and do this in the recursion 并在递归中执行此操作
quicksort(arr,left,end)
quicksort(arr,start,right)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.