I think your problem is that you do not fully understand recursion. At least that's what your description of the question seems to be.
In any case, I tried to just follow your program, keeping traces of all variables. Hope this helps:
arr left right ij pivot ----------------- ------- -------- ------- ----- ---------- [10,5,3,22,11,2] 0 5 0 5 arr[2] = 3 [2,5,3,22,11,10] 1 4 3 2 [2,3,5,22,11,10] 2 1
The while loop is complete because i<=j
now false
( 2 > 1
).
The first condition, left < j
( 0 < 1
), is true
, so you call quicksort
again recursively: quicksort(arr, 0, 1)
- this means that now you will sort the array [2,3]
, which is already sorted, so there’s nothing will happen:
arr left right ij pivot ----------------- ------- -------- ------- ----- ---------- [2,3,5,22,11,10] 0 1 0 1 arr[0] = 2 0 [2,3,5,22,11,10] 1 -1
The while loop condition is now false
. The first condition left < j
is false
(because 0 > -1
), and the second condition i < right
also false (because 1 == 1
). Thus, this call is completed, and you will return to where you were. Was that so? The first condition of the table above. Now the state of the variables and parameters:
arr left right ij pivot ----------------- ------- -------- ------- ----- ---------- [10,5,3,22,11,2] 0 5 2 1 3
The second condition is checked (since the next line is true). Its value is also true, since the condition i < right
( 2 < 5
). So, now you are quicksort
again recursively: quicksort(arr, 2, 5)
- this means that now you are sorting the array [3,22,11,10]
:
arr left right ij pivot ----------------- ------- -------- ------- ----- ---------- [2,3,5,22,11,10] 2 5 2 5 arr[3] = 22 3 [2,3,5,10,11,22] 4 4 5
i > j
, so we exit the while loop.
The first condition, left < j
( 2 < 4
), is true
, so we call quicksort(arr, 2, 4)
to sort [5,10,11]
, which is already sorted. I will skip this part as it does not modify the array at all.
When the recursive call is complete, we will return to where we were, and now the second condition will be checked. i < right
( 5 < 5
) false
And so we are done.
The original quicksort
call quicksort
complete and the array is sorted.