1/31/2024
QuickSort :: 2nd attempt
This is my second attempt at using QuickSort to solve the Sort an Array problem Here is what I learned.
What happens right before hi
crosses lo
?
On the iteration right before hi
crosses lo
, they are next to each other. In other words, we have hi === lo + 1
.
Then, in the partition
function, leftP
is assigned to lo
then increases by one and reaches hi
, thus a[leftP] > a[pivotP], the loop stops.
Also, in the partition
function, rightP
is assigned to hi +1
, then decreases by one, still greater than pivot, decreases by one again, now it equals to lo
, less than pivot and stops.
The if statement right after that escapes the while(true)
loop,then the pivot is swap with lo
.
Now, we have pivot === lo, thus, the first sort returns because hi < lo
and the second sort returns because hi === lo
.
Why the statement if(leftP >= rightP) break;
is put inside the while loop?
Because two while loops right before it can make the two pointers cross each other. If there is not the if statement right there to stop, the swap statement right after that can mess thing up.