balt2
balt2

Reputation: 75

Python while loop getting stuck during quicksort

I am trying to write a quicksort function in Python using a while loop and for some reason, my loop will cause sublime to shut down if I don't increase i during EACH iteration (which is not something I want to do as index 0 of the array may change during the loop). Any ideas about why this may be happening or what is wrong with my while loop? Thanks for the help! I bet I am just being dumb somewhere.

from random import randint

def quicksort(arr):
    print(arr)
    pivot = arr[randint(0, len(arr)-1)]
    i = 0
    while i < len(arr):
        print('value', arr[i])
        print('pivot', pivot)
        if arr[i] < pivot:
            arr.append(arr[i])
            del arr[i]
        else:
            i += 1
        print(arr)
    print(arr)

arr1 = [3,86,5,75,2,58,6,4,9,7,87,2,1,6,9,90,65,5,1,890]
quicksort(arr1)

Upvotes: 2

Views: 278

Answers (1)

DYZ
DYZ

Reputation: 57033

If the last element of the list is smaller than the pivot, your function will append it to the end and delete again forever. In fact, this is true even when all the remaining elements are smaller than the pivot.

Upvotes: 2

Related Questions