U
U
UID_B Nintendo2020-04-13 18:19:16
Python
UID_B Nintendo, 2020-04-13 18:19:16

Where is the implementation error of the QuickSort algorithm?

import random

def quickSort(arr, start, end):
    if start >= end:  # if len(arr) < 2
        return arr
    else:
        divideIndex = partition(arr, start, end)
        quickSort(arr, start, divideIndex - 1)
        quickSort(arr, divideIndex, end)

def partition(arr, head, tail):
    left = head
    right = tail
    pivot = arr[(head + tail) // 2]  # mid

    while right >= left:
        # looking through the array from the left
        while arr[left] <= pivot:
            left = left + 1
        # looking through the array from the right
        while arr[right] > pivot:
            right = right - 1
        # found a couple of elements that can be exchanged.
        if left <= right:
            swap(arr[right], arr[left])
            # move the left and right wall
            left = left + 1
            right = right - 1
    # return one elements if not found a couple
    return left

def swap(arr1, arr2):
    temp = arr1
    arr1 = arr2
    arr2 = temp

# Generator random variables
deck = list(range(50))
random.shuffle(deck)


start = 0
end = len(deck) - 1
print(quickSort(deck, start, end))

When I run the code, it tells me this: RecursionError: maximum recursion depth exceeded in comparison

Answer the question

In order to leave comments, you need to log in

2 answer(s)
@
@ibKpoxa, 2020-04-13
_

https://stackoverflow.com/questions/3323001/what-i...

A
Andrew, 2020-04-14
@wite27

Check the cycle conditions again:
1.

while arr[left] <= pivot:
            left = left + 1

What will happen to the left variable if the array consists of the same numbers? For example, try calling 2. The swap function doesn't work quite the way you'd expect: numbers are passed into it, which become local variables inside the function, so the assignments that occur in it only affect those local variables, not the original array. Try 1) "inlining" the function into the call site (replacing the call site with the function body), or 2) rewriting the function so that it takes the arr array as input , and two indexes, and performs an exchange over the array (you can read more about this at https ://docs.python.org/3/faq/programming.html#how... , https://stackoverflow.com/questions/986006/how-do-... ) print(quickSort([1, 1, 1, 1], 0, 3))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question