Dear all,
The following is the quick sort function which i have seen in my note
book
how good is this function ?
void sort(int a[], int begin, int end)
{
int pivot,l,r;
if( (end -begin) > 1)
{
pivot = a[begin];
l = begin + 1;
r = end;
while(l < r)
{
if(a[l] <= pivot)
l++;
else
{
r--;
swap(&a[l],&a[r])
}
}
l--;
swap(&a[begin],&a[l]);
sort(a,begin,l);
sort(a,r,end);
}
}
For the discussion below, imagine that an array of 'n' elements is a line of
boxes lying on its side, like this:
[0][1]....[n-1][n]
Left is towards the nth or last element and right is towards the 0th or
first element.
As far as code quality, I would say it is not a good implementation of
quicksort. Pete explained the right way to do it elsethread (actually, the
_real_ right way is even a bit quirkier, as Pete well knows). At any rate,
for a simple routine like this I would say that it is *ideal* for one
particular purpose:
Understanding, fundamentally, how the sort routine works. You can see at a
glance that it is grabbing an element (the choice of which element is a poor
one, but that is not important for understanding how quicksort works) and
then moving smaller things to the left and larger things to the right. That
gives you two piles now, where you used to have one pile. One pile (the one
on the left) is a pile of little things. And the other pile (the one on the
right) is a pile of little things. You can easily imagine that if we repeat
this procedure on the pile of big things and the pile of little things, that
we will then have 4 ordered piles of big things and little things. Then we
will get 8 piles and then 16 ordered piles (smallest on the left to largest
on the right) and so on. Eventually, these piles will have a size of 1
element each and our data will be sorted.
I would encourage you to try the routine out with some data in a debugger.
(Aside: If you find a bug, then fix it. ) The main thing that you will be
driving for is to understand what is going on. Then, after you understand
it, give it an array full of data that is already correctly ordered. You
will see that it behaves badly. Ask yourself, "How could I make it behave
in a more civilized manner if the data is already in order?" This is a
problem that other people have already worked out, but it will be better for
your understanding to work it out yourself.
IMO-YMMV.
P.S.
Your question is not a C question, but a programming question. So, the next
time you have a puzzle like this one, try it on newsgroup
Many of the regulars of this group frequent that one
as well and you will find that a well posed question in a well targeted
newsgroup can elicit well posed answers better than asking the wrong
questions in the wrong place.