I have two days trying to figure out why my quicksort function returns all but two elements sorted in correct order.
With the Input
quicksort([0,7,3,11,23,87,999,1023,12,713,5,6,9])
Outputs
[0, 6, 3, 5, 7, 9, 11, 12, 23, 87, 713, 999, 1023]
What do you think is wrong with the function?
def quicksort(array):
#Base case
if len(array) <= 1:
return array
#Choose pivot always at the left part and partition array around it
Pivot = partition(array,0,len(array));
#Add values for left and righ arrays
left = array[:Pivot]
right = array[Pivot+1:]
#Add recursive calls
left = quicksort(left)
right = quicksort(right)
#Append Pivot at the end of left array
left.append(array[Pivot])
return left+right
For matters of completion I'm adding the partition function but I'm almost sure the issue is not there.
def partition(array,left,right):
#If pivot is not on leftmost, swap to make it leftmost
Pivot = array[left]
i = left+1
for j in range(left+1,right):
if array[j] < Pivot:
#Swap array[j] and array[i]
array[j], array[i] = array[i], array[j]
i += 1;
#Swap pivot and A[i-1]
array[left], array[i-1] = array[i-1], array[left]
return left