I am extremely new to Python and i am trying my hand in Algorithms. I was just trying my hands in the in place sorting of an array using quicksort algo.
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 :
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.