I’ve been trying to understand quick sort by implementing it myself in Python using the left and right pointer method. I can’t seem to get it to work and looking at visualizations online, I’m failing to understand how quicksort works when operating on a list of length 2. According to most sources I’ve read, you should select a pivot and your left and right pointers should not include that pivot value when moving left/right. When a list is of length 2, you select a pivot and are left with a list of length 1 and left/right immediately meet. How would quicksort ever sort the input [5,4]?
Here is the Python code I have written:
def quicksort(arr, low, high):
if low < high:
pivot_index = partition(arr, low, high)
quicksort(arr, low, pivot_index-1)
quicksort(arr, pivot_index+1, high)
return arr
def partition(arr, low, high):
# select last element as pivot
pivot_index = high
pivot = arr[high]
left_wall = low
# exclude pivot from left/right searching
right_wall = high-1
# keep searching until next swap point found
while left_wall < right_wall:
# if left wall value is not greater than pivot, keep searching
while arr[left_wall] <= pivot:
left_wall += 1
# if right wall value is not less than pivot, keep searching
while arr[right_wall] >= pivot:
right_wall -= 1
if left_wall < right_wall:
# perform swap
temp_left_wall = arr[left_wall]
arr[left_wall] = arr[right_wall]
arr[right_wall] = temp_left_wall
# swap pivot with right wall
arr[pivot_index] = arr[right_wall]
arr[right_wall] = pivot
return right_wall
quicksort([5,4,3,2],0,3)
Can someone help me understand what I am not understanding about the quicksort process?