Reversing order of quicksort

F

flipflop

Sorry if this is a very faq - I haven't seen the answer here though.
The quicksort code below sorts an array from large to small. I simply
want it to reverse the sort order: small to large, but can't see how.
I've walked through it on paper but am just not seeing it.

qsort(double *item,int array_size)
{
qsort_recurse(item,0,array_size-1);
}

qsort_recurse(double *item,int left,int right)
{
int i,j;
double x,tmp;

i=left;
j=right;
x=item[(left+right)/2];
do {
while (item>x && i<right) i++;
while (x>item[j] && j>left) j--;
if (i<=j) {
tmp=item;
item=item[j];
item[j]=tmp;
i++;
j--;
}
} while (i<=j);
if (left<j) qsort_recurse(item,left,j);
if (i<right) qsort_recurse(item,i,right);
}
 
M

Martin Dickopp

Sorry if this is a very faq - I haven't seen the answer here though.
The quicksort code below sorts an array from large to small. I simply
want it to reverse the sort order: small to large, but can't see how.
I've walked through it on paper but am just not seeing it.

qsort(double *item,int array_size)

You cannot name your function `qsort', because a `qsort' function
already exists in the standard C library. Speaking of which, is there
any particular reason why you cannot or don't want to use the `qsort'
function in the standard C library?

As to your question, just invert all comparisons of the elements to be
sorted. For example,
while (item>x && i<right) i++;
while (x>item[j] && j>left) j--;


should become

while (item<x && i<right) i++;
while (x<item[j] && j>left) j--;

Martin
 
C

CBFalconer

Martin said:
flipflop writes:
.... snip ...

As to your question, just invert all comparisons of the elements
to be sorted. For example,
while (item>x && i<right) i++;
while (x>item[j] && j>left) j--;


should become

while (item<x && i<right) i++;
while (x<item[j] && j>left) j--;

^^^^^^^^^
and then remove the underlined clauses in both lines, which cannot
have any effect (other than to slow operation) when you consider
how x was generated.
 
M

Martin Ambuhl

flipflop said:
Sorry if this is a very faq - I haven't seen the answer here though.
The quicksort code below sorts an array from large to small. I simply
want it to reverse the sort order: small to large, but can't see how.

Change the sense of the comparison. '<' for '>' etc. Trivial, non?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top