views:

159

answers:

5

Hi I was wondering that if you had an array of integers, how you would use sort it using selection sort in descending order. I know how to do it in ascending order but I don't know how to do in it descending order.

Thanks!

+1  A: 

Selection sort is a comparison sort. To sort in reverse order, simply reverse the comparison.

In other words, instead of using >, use <.

Mark Byers
A: 

You do it the same way you'd do it in ascending order, except you always pick the largest element instead of the smallest.

sepp2k
A: 

Hi

Selection sort is a comparison sorting technique (you use a comparison operator to obtain an order which can be ascending or descending). So to get the descending order you just flip the comparison operator from < to >.

You might want to read more on selection sort.

I hope this helps.

cheers

Andriyev
+1  A: 

Selection sort is simple you look at the first element and if it is > element[i] then you swap it. For instance:

8 5 1 9

Start at element 8..look at next element its smaller so swap it:

5 8 1 9

Now look at the following element 1, it too is smaller then 5 swap positions

1 8 5 9

Finally 9 > 1 move to next element (8) and compare...keep doing it till you have

1 5 8 9

Now to do the opposite sort by descending is the same algorithim, but you simply check if it is > rather then <.

For instance,

1 9 5 8

Start at 1, is 9 > 1, yes so swap it:

9 1 5 8

Keep going..move to second digit is 1 < 5, yes swap it:

9 5 1 8

Keep doing this till you have

9 8 5 1

Here's some pseudocode, it is not Java but C but should help you understand that if you can implement selection sort for ascending, then you can do it for descending:

 while(pTemp2 != NULL)
   {   
       //we implement a selection sort 
       //check if incoming node->datum with each node in the list
       //swap values if >
      if (pTemp2->datum > pTemp->datum)
         {
         //swap the values
         int temp = pTemp->datum;
         pTemp->datum = pTemp2->datum;
         pTemp2->datum = temp;
         }
         //advance the pointer
      pTemp2=pTemp2->next;
   }
JonH
A: 

If you understand how selection sort works, it should be trivial to make it sort in descending order. It might be a good idea to go through your notes/book again, and follow how selection sort actually works.

To sort in ascending order, you pick out the minimum element in each step. To sort in descending order, simply pick the maximum element. Thus, in the first step you pick the largest, in the second you pick the next largest and so on, yielding a list sorted from largest to smallest.

MAK