The functions below are an implementation of Quick sort. Here we take the last element as a pivot.
I understood the partition
function(where the pivot comes to its sorted position) but I can't understand the recursive function qs
. The function qs
calls itself recursively to solve the left side by qs(a,start,pi-1)
and the right of the partition by qs(a,pi+1,end)
.
Does it the solve the left and then the (left of the left) then (the left of(the left of the left), etc, and then left, left...right, etc. Or does it alternate by solving the left side and then right side.
PS: I want to know whats happening inside the computer, the mechanism of this recursion of quick sort. The program is working but I want to know how it works.
int partition(int *a, int start, int end)
{
int pivot=a[end];
int pi=start;
for(int i=start; i<end; i++)
{
if(a[i]<=pivot)
{
swap(a[i],a[pi]);
pi++;
}
}
swap(a[pi], a[end]);
return pi;
}
void qs(int*a, int start, int end)
{
if(start<end)
{
int pi=partition(a,start,end);
qs(a,start,pi-1);
qs(a,pi+1,end);
}
}