-5

This is the code for Quick sort in which i used assignment to swap the values.

def partion(arr,low,high):
  partion_index=low
  pivot=arr[partion_index]

  while (low < high):
    while low < len(arr) and (arr[low]<=pivot):
      low+=1
    while (arr[high]>=pivot):
      high-=1
    if (low < high):
      arr[low],arr[high]=arr[high],arr[low]

  pivot,arr[high]=arr[high],pivot
  return high   
def quickSort(arr,low,high):
  if(low <high):
    p=partion(arr,low,high)
    quickSort(arr,low,p-1)
    quickSort(arr,p+1,high)

This is producing the wrong results. When i tried using swap function for the same job it worked.

def swap(a, b, arr):
    if a!=b:
        tmp = arr[a]
        arr[a] = arr[b]
        arr[b] = tmp

def partion(arr,low,high):
  partion_index=low
  pivot=arr[partion_index]

  while (low < high):
    while low < len(arr) and (arr[low]<=pivot):
      low+=1
    while (arr[high]>=pivot):
      high-=1
    if (low < high):
      swap(low, high, arr)
      
  swap(partion_index, high, arr)
  return high

Why is it so?

4
  • 1
    The second-to-last lines pivot,arr[high]=arr[high],pivot and swap(partion_index, high, arr) in each version of partition() do not appear to be equivalent. Commented Jul 25, 2024 at 20:38
  • Maybe try arr[partition_index],arr[high]=arr[high],pivot instead of pivot,arr[high]=arr[high],pivot? Commented Jul 25, 2024 at 20:45
  • Welcome to SO! Please read minimal reproducible example - there's a lot of code here; it's expected that you reduce it to the bare minimum before asking a question here. Commented Jul 25, 2024 at 21:25
  • (There is a Style Guide for Python Code.) Commented Jul 26, 2024 at 4:46

1 Answer 1

0

When swapping the pivot, you are swapping with the pivot variable and not the array[partion_index]. Changing it to the below should make it equivalent to the swap approach.

array[partion_index], arr[high] = arr[high], array[partion_index]

Note: I didn't really check the overall validity of the QuickSort implementation though.

Sign up to request clarification or add additional context in comments.

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.