How can I sort numbers from largest to smallest in an array?

Viewed 639

I was able to sort the numbers in the matrix from smallest to largest, but I could not sort them from largest to smallest. please help...

int[] list = new int[4];

System.out.println("Enter the numbers of array: ");
for (int i = 0; i < list.length; i++)
    list[i] = kbd.nextInt();

for (int index = 0; index < list.length; index++) {
    int minIndex = index;
    for (int i = index + 1; i < list.length; i++) {
        if (list[i] < list[minIndex])
            minIndex = i;
    }
    int temp = list[index];
    list[index] = list[minIndex];
    list[minIndex] = temp;
}

System.out.println("Numbers after sorting: ");
for (int j : list) System.out.print(j + " ");
3 Answers
public static void main(String... args) {
    int[] arr = new int[20];
    Random random = new Random();

    for (int i = 0; i < arr.length; i++)
        arr[i] = random.nextInt(10);

    System.out.println(Arrays.toString(arr));
    int[] reverseSortedArr = Arrays.stream(arr)
            .boxed()
            .sorted(Comparator.reverseOrder())
            .mapToInt(i -> i)
            .toArray();
    System.out.println(Arrays.toString(reverseSortedArr));
}

Output:

[9, 0, 8, 1, 4, 7, 3, 6, 4, 6, 7, 6, 2, 3, 8, 0, 1, 3, 5, 2]
[9, 8, 8, 7, 7, 6, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 1, 1, 0, 0]

Your method is fine. No need to change it except below. All you need to do is reverse the condition of the sort. See the comment in the following code segment.

for (int i = index + 1; i < list.length; i++) {
    if (list[i] < list[minIndex]) // change < to >
        minIndex = i;
}
import java.util.Arrays;
import java.util.Comparator;
Integer[] array = ...
Arrays.sort( array, Comparator.reverseOrder() );

Now the elements in the arry are sorted

Related