while implementing quick sort i thought that when there’s two or three element in the arr there’s no need to continue dividing the arr since if you just partitioned the pivot you will end up with a sorted array
the problem is after adding started fluctuating between
if e-s == 2 or e-s == 1: partition(arr,s,e) return
without the if condition above the code works fine
import random
def quickSort(arr,s,e):
if s >= e: return
if e-s == 2 or e-s == 1:
partition(arr,s,e)
return
x = randPartition (arr,s,e)
quickSort(arr,s,x-1)
quickSort(arr,x+1,e)
def partition(arr,s,e):
pivot = arr[s]
x = s
for i in range (s+1,e+1):
if arr[i] < pivot :
x+=1
arr[x],arr[i]=arr[i],arr[x]
arr[s],arr[x] = arr[x],arr[s]
return x
def randPartition(arr,s,e):
x = random.randint(s,e)
arr[x],arr[s] = arr[s],arr[x]
return partition(arr,s,e)
arr = [1,5,0,3,-15,12,96,99,1500,-1500,66,120]
quickSort(arr,0,len(arr)-1)
print(arr)
output
[-1500, -15, 0, 1, 3, 12, 5, 66, 96, 99, 120, 1500]
[-1500, -15, 0, 1, 5, 3, 12, 66, 96, 120, 99, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 120, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 99, 96, 120, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 1500, 120]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 120, 99, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 120, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 120, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 1500, 120]
[-1500, -15, 0, 3, 1, 5, 12, 66, 96, 99, 120, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 120, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 1500, 120]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 120, 1500]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 1500, 120]
[-1500, -15, 0, 1, 3, 5, 12, 66, 96, 99, 120, 1500]
>Solution :
The reason why the code doesn’t work as expected with the additional if condition is because you are only partitioning the array but not sorting it in ascending order.
When you partition the array with two or three elements, you may end up with a partially sorted array but not completely sorted. For example, if you have [5,1,3], partitioning it will give you [3,1,5]. This is not a completely sorted array.
Therefore, you need to continue dividing the array until you get to a point where each sub-array has only one element. At that point, you will be sure that the array is sorted in ascending order.
In summary, the extra if statement will not be helpful because it will not sort the array properly, so it’s best to stick to the standard quicksort algorithm even for arrays with only two or three elements.