'''
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?