I have doubt in algorithm.! Quick_Sort using recursion

ll partition(ll *a,ll s,ll e)
{
ll i=s-1;
ll j=s;
ll pivot=a[e];
for(;j<=e-1;j++)
{
if(a[j]<=pivot)
{
i++;
swap(a[i],a[j]);
}
}
swap(a[i+1],a[j]);
return i+1;
}

in partition loop why we run loop from j=s to e-1 and not e?

what will be the problem if we run j<=e instead of j<=e-1.

Thank you.

hello @dhruvilcodes

a[e] is the pivot element itself.

when the loop will over then value of j will be e.

so this line is nothing but swap(a[i+1],a[e]) which is correct . we want to do exaclty same thing.

if u will iterate till j=e then there is no need of external swap function.

1 Like

check this implementation for clarity->

1 Like

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.

1 Like