0

I am reviewing sorting algorithms and tried to write Quick Sort algorithm. The simplest implementation that I found is written in Java and I have run it to confirm that it works. However, when I tried to rewrite it in Python, it seems to be off in some way. I have spent a few hours trying to debug this as to why it doesn't work, but it is quite difficult to debug because it's recursion based algorithm... If someone could tell me what's wrong with my implementation below, that would be very helpful. Thank you!

def partition(arr, start, end):
    piv = (start + end)//2
    pivotVal = arr[piv]

    left = start
    right = end

    while left <= right:
        if arr[left] < pivotVal:
            left += 1

        if arr[right] > pivotVal:
            right -= 1

        if left <= right:
            temp = arr[left]
            arr[left] = arr[right]
            arr[right] = temp
            left += 1
            right -= 1

    return left

def quickSort(arr, left, right):
    piv = partition(arr, left, right)

    if left < (piv - 1):
        quickSort(arr, left, piv - 1)

    if piv < right:
        quickSort(arr, piv, right)

myList = [54,26,93,17,77,31,44,55,20] # this doesn't get sorted quite right
quicksort(myList, 0, len(myList)-1)
print(myList)

2 Answers 2

1

Try:

    while left <= right:
        while arr[left] < pivotVal:
            left += 1

        while arr[right] > pivotVal:
            right -= 1

        if left <= right:
            temp = arr[left]
            arr[left] = arr[right]
            arr[right] = temp
            left += 1
            right -= 1
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I can't believe that's what I have been missing!! Thanks a lot!!! That's why it's good to not code for more than a few hours at one sitting. :D
0

This might help u to understand,

def partition(arr,left,right):
  i = (left - 1)
  pivot =arr[right]
  for j in range(left,right):
    if arr[j]<= pivot:
      i += 1
      arr[i],arr[j] = arr[j],arr[i]
  arr[i+1],arr[right]=arr[right],arr[i+1]
  return(i+1)

def quickSort(arr, left, right):
  if left < right:
    piv = partition(arr, left, right)
    quickSort(arr, left, piv - 1)
    quickSort(arr, piv+1, right)

arr = [54,26,93,17,77,31,44,55,20,67]
quickSort(arr, 0, len(arr)-1)
print(arr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.