My thoughts: i'm trying to implement quick sort with python. i set the first element as pivot. if the element of left mark is larger than pivot then i start moving the right mark to find an element smaller than pivot and then swap. if right mark is smaller than left mark, swap pivot with the element of right mark. then separate the list with pivot. and repeat the step
Question: my code can separate the list into two lists as i imagined. but when it returns it somehow copy the elements several times and made it wrong. i'm not familiar with recursion and can't find the problem.
def quick_sort(lst):
front = []
rear = []
temp = 0
pivot = lst[0]
i = 1 #leftmark
j = len(lst)-1 #rightmark
if len(lst) == 1:
return lst
while i<=j:
if lst[i]<pivot:
i+=1
else:
if lst[j]>pivot:
j-=1
elif lst[j] == pivot:
break
else:
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
'''if j<i (rightmark < leftmark) swap pivot with position j'''
temp = pivot
pivot = lst[j]
lst[j] = temp
lst[0] = pivot
front = lst[0:j+1]
rear = lst[i:len(lst)+1]
return quick_sort(front) + [pivot] + quick_sort(rear)