0

'''

def swap_elements(my_list, index1, index2):
    my_list[index1], my_list[index2] = my_list[index2], my_list[index1]

def partition(my_list, start, end):

    p = end
    b= start
    for i in range(len(my_list)):
        if my_list[i] < my_list[p]:
            swap_elements(my_list, i, b)
            b += 1
    swap_elements(my_list, b, p)
    p = b
    return p
            
def quicksort(my_list, start, end):
    if end - start < 1:
        return my_list
    else: 
        p = partition(my_list, start, end)
        partition(my_list, start, p-1)
        partition(my_list, p+1, end)
'''

When I use this code because of second function 'partition' there is a IndexError: list index out of range. However When I change the 'partition' code like this '''

def partition(my_list, start, end):
    i = start
    b = start
    p = end

    while i < p:
        if my_list[i] <= my_list[p]:
            swap_elements(my_list, i, b)
            b += 1
        i += 1

    swap_elements(my_list, b, p)
    p = b

    return p

''' It works. I don't know the differences between for and while. Does anyone knows the answer?

1 Answers1

1

It has nothing to do with the choice of the for vs. while loop, since they are functionally the same. It has everything to do with the bounds. You have written the following line for the for loop:

for i in range(len(my_list)):

whereas you have written the following lines for the while loop:

i = start
b = start
p = end

while i < p:

You can see that these lines are not the same. In the for loop, you are iterating over the length of the entire array, whereas in the while loop, you are iterating from the bounds you are given. Therefore, you should modify the range of the for loop like so:

p = end
b= start
for i in range(start, p):

Also, you should modify the quicksort method like so to ensure that it runs:

    p = partition(my_list, start, end)
    quicksort(my_list, start, p-1)
    quicksort(my_list, p+1, end)
    return my_list
Hossmeister
  • 166
  • 1
  • 9
  • Calling the for and while loop functionally the same is a bit of an oversimplification of [the differences between the two](https://stackoverflow.com/questions/920645/when-to-use-while-or-for-in-python). – 0x263A Aug 13 '21 at 05:37
  • @MrR True, my point was that there is no difference in the actual internal behavior of a `for` vs `while` loop. The OP seemed to understand that they had to manually iterate in the case of the `while` loop, and the issue with the `for` loop was simply with the chosen bounds. – Hossmeister Aug 13 '21 at 14:30