-2

I've recently learned how to sort arrays in ascending order with this code in Java;

int swapIndex,temp; 
for(int index=0; index<=array.length-2; index++) { 
    swapIndex = index; 
    for(int i=index+1; i<=array.length-1; i++) 
       if(array[i]<array[swapIndex]) swapIndex = i; 
    temp = array[index]; array[index] = array[swapIndex]; 
    array[swapIndex] = temp; 
  } 
}

Can somebody please tell me how to I can use this code but sort in descending order? Best regards

2 Answers2

0

Why don't you just use something like this instead?

Arrays.sort(array, Collections.reverseOrder());
Christoffer
  • 7,470
  • 9
  • 39
  • 55
0

Just flip the sign in your if statement

int swapIndex,temp; 
for(int index=0; index<=array.length-2; index++) { 
    swapIndex = index; 
    for(int i=index+1; i<=array.length-1; i++) 
       if(array[i] > array[swapIndex]) swapIndex = i; //change the sign
    temp = array[index]; array[index] = array[swapIndex]; 
    array[swapIndex] = temp; 
  } 
}

This way, you're only swapping if the element at i is greater than the one at swapIndex, so the smaller numbers get moved further to the right.

not_a_bot
  • 2,332
  • 2
  • 19
  • 33