1

So here I have a selection sort to order values from lowest to highest, how would I change that so it orders the values from highest to lowest?

int min;
for (int i = 0; i < array.length; i++) {
    // Assume first element is min
    min = i;
    for (int j = i + 1; j < array.length; j++) {
         if (array[j] < array[min]) {
              min = j;
         }
    }

    if (min != i) {
       final int temp = array[i];
       array[i] = array[min];
       array[min] = temp;
    }
itsATextArea.append(array[i] + "\n");
}
user2383438
  • 11
  • 1
  • 1
  • 5

2 Answers2

2

You just need to change the signs in the code

if (array[j] > array[max])
{
    //assign it here
    max = j;
}

following is how the code looks after the modification.

int max;
for (int i = 0; i < array.Length; i++)
{
    // Assume first element is max
    max = i;
    for (int j = i + 1; j < array.Length; j++)
    {
        if (array[j] > array[max])
        {
            max = j;
        }
    }

    if (max != i)
    {
       int temp = array[i];
       array[i] = array[max];
       array[max] = temp;
    }
}
1

How about:

java.util.Arrays.sort(array);
java.util.Arrays.reverse(array);
user1676075
  • 3,056
  • 1
  • 19
  • 26
  • 1
    Or, if you use the appropriate comparator function with the `sort()` there is no need to reverse the array afterwards. See [here](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html), for instance. – Simon May 16 '13 at 01:51