Sort Arrays of Primitive Types in Descending Order

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.

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.

Sorting int array in descending order

For primitive array types, you would have to write a reverse sort algorithm:

Alternatively, you can convert your int[] to Integer[] and write a comparator:

public class IntegerComparator implements Comparator<Integer> {

@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}

or use Collections.reverseOrder() since it only works on non-primitive array types.

and finally,

Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());

//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

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.

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));
}
}

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);
}

Optimized and efficient way to sort int[] primitive array in Java

First off, you code has a few issues with the 2nd and 3rd line of the for loop, since the first index it tries to access is "6", which doesn't exist. The last line of the for loop has an extra ]

So, I think this is what you meant, feel free to correct me if I've got this wrong!

 for(int i = 0; i <= arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}

But if you want to maintain lower space complexity, I think the in-place modification you have is pretty close to as small as you're going to get. Even with streams, it's not going to get much shorter (but will get somewhat subjectively messier).

Also, not to complicate things further, but if your array uses a sufficiently small range (edit: and more importantly, you know that range beforehand), you can use counting sort, which is O(n+k) time complexity vs. Arrays.sort()

java comparator for arrays sort

There is no method that takes a primitive array like int[] nums and sorts it in descending order. There are some that take an array of Objects, like sort(T[] a, Comparator<? super T> c) - but primitives are not Objects1.

The most straightforward method is likely to simply sort(int[] input) your array in ascending order, then reverse the resulting array. The sort is likely to take significantly longer than the reverse, so this method should perform well. Alternately, you may be able to modify the consuming code so that it deals with the array in ascending order, or you could wrap the array in a List and then use a reversed view.

There are lots of other options as well.


1 You could, in principle, convert your int[] into an Integer[], by boxing each underlying int element, but you would pay a large performance penalty and a huge memory (increasing the memory used by about 10x) and garbage penalty to do so.

Sort int array in descending order using java 8 features (stream, lambda, etc)

With guava you could simply write

Ints.asList(a).sort(Comparator.reverseOrder());

It may be not so efficient since it requires boxing int to Integer, but it is elegant one-liner.

You can also write something like

int[] sorted = IntStream.of(a)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();

but this also suffers from boxing and it needs to create new array.

Anyway I doubt you will find nice solution in standard Java free of boxing since Comparator<T> can accept only objects. For now best way would be using Arrays.sort and reverse its order manually.



Related Topics



Leave a reply



Submit