Java Array Sort Descending

Java Array Sort descending?

You could use this to sort all kind of Objects

sort(T[] a, Comparator<? super T> c) 

Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.

How to sort integer array in ascending and descending order using lambda only in java

You could sort the input of type Integer[] as :

Integer[] arr2 = new Integer[] {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());

or possibly with primitive types as :

int[] arr2 = new int[]{54, 432, 53, 21, 43};
int[] sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();

or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :

int[] sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();

Edit: For an in-place ascending order sort, you just need to perform :

int[] arr2 = new int[]{54, 432, 53, 21, 43};
Arrays.sort(arr2);

Array Sorting Descending Order

There's no sort method in Arrays class that accepts an int[] and a Comparator. The sort methods in the Arrays class that accept a Comparator require an array of reference type (while an int[] is an array of a primitive type).

If you change the type of your scores array from int[] to Integer[], your code will work, since the method public static <T> void sort(T[] a, Comparator<? super T> c) of the Arrays class will match your Arrays.sort(scores, Collections.reverseOrder()); call.

final int EXAMS = 5;
Integer[] scores = new Integer [EXAMS]; // the only required change
for (int index = 0; index < EXAMS; index++) {
System.out.println("Enter the score for " + (index+1) +":");
scores[index] = kb.nextInt();
if (scores[index] < 0){
System.out.println("The number you have entered is invalid.");
scores[index] = kb.nextInt();
}
}
Arrays.sort(scores, Collections.reverseOrder());
System.out.println("The sorted int array is:");
for (int number : scores) {
System.out.println("Number = "+ number);
}

Sort large arrays of primitive types in descending order

Java Primitive includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:

double[] array = new double[1048576];
...
Primitive.sort(array, (d1, d2) -> Double.compare(d2, d1), false);

If you're using Maven, you can include it with:

<dependency>
<groupId>net.mintern</groupId>
<artifactId>primitive</artifactId>
<version>1.2.1</version>
</dependency>

When you pass false as the third argument to sort, it uses an unstable sort, a simple edit of Java's built-in dual-pivot quicksort. This means that the speed should be close to that of built-in sorting.

Full disclosure: I wrote the Java Primitive library.

sorting array of arrays in descending order using arrays.sort function is resulting in errors in java

As mentioned in comments, you are sorting by inner element, which is int[], so you need Comparator<int[]>.

public class Solution {

public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
Arrays.sort(input, new Comparator<int[]>() {

@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
System.out.println(Arrays.deepToString(input));
}
}

Note return Integer.compare(o2[1], o1[1]);, second parameter is compared to first in order to achieve descending order.

You could also achieve same effect using lambda, to make it shorter and more readable.

public class Solution {

public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
System.out.println("Initial array - " + Arrays.deepToString(input));
Arrays.sort(input, (o1, o2) -> Integer.compare(o2[1], o1[1]));
System.out.println("Sorted array - " + Arrays.deepToString(input));
}
}

Java array sort descending and print their element number

You could work with a Map with the element as the key, and the index as the value. You'd first have to create this map with a for loop

Map<Integer, Integer> indexLookUp = new HashMap<>();
for(int i = 0; i < array.length; i++) {
map.put(array[i], i);
}

Then you can sort the array:

Arrays.sort(array);

You don't need the reversing part, as you can just iterate the array backwards. And then print out the index for the element via the map lookup:

for(int i = array.length - 1; i >= 0; i--) {
System.out.println("Element: " + array[i] + ", previous index: " + map.get(array[i]));
}

Java - Descending order

Arrays.sort(T[] a, Comparator c) doesn't work with primitive types arrays.

You may simply change your array, to an array of Integer :

Integer arrays[]={4,3,8,9,0,44,12};

why Arrays.sort() can't sort primitive type array in descending order?

Look at the signature of the Arrays#sort method you are trying to use

  public static <T> void sort(T[] a, Comparator<? super T> c) {
...
}

Where <T> the class of the objects to be sorted in the Array. Primitive int can't be a convert class.



Related Topics



Leave a reply



Submit