Doubt regarding Quick sort

At the time of swapping why are we putting a condition of
if(left <= right) .
Can you explain me , with help of an example ?

lets understand through this example.
array: 2 4 3 5 6 9 43 23 21
pivot = 6
now try to run partition() method.

  1. initially left=0, right = 8, pivot = arr[4]=6
  2. since left<=right is true, we will enter while loop
  3. left will stop when arr[left] = 9, it means left = 5
  4. right will stop when arr[right] = 5, it means right = 3
    as you can observe that the array was already partitioned.
    now after step4, if we wont check that left<=right, we will swap 9 and 5 unnecessary and end up with wrong result.

thanks

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.