How to sort an array of ints using a custom comparator?
If you can't change the type of your input array the following will work:
final int[] data = new int[] { 5, 4, 2, 1, 3 };
final Integer[] sorted = ArrayUtils.toObject(data);
Arrays.sort(sorted, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
// Intentional: Reverse order for this demo
return o2.compareTo(o1);
}
});
System.arraycopy(ArrayUtils.toPrimitive(sorted), 0, data, 0, sorted.length);
This uses ArrayUtils
from the commons-lang project to easily convert between int[]
and Integer[]
, creates a copy of the array, does the sort, and then copies the sorted data over the original.
Sort integer array based on custom comparator
Make sure to declare the buffer
attribute as an Integer[]
, because you defined the comparator for the Integer
type, not for the int
type - and the sort()
method that receives a Comparator
will only work for arrays of object types, not for arrays of primitive types such as int
.
Be aware that an int[]
can not be automatically converted to Integer[]
, it might be necessary to explicitly create a new Integer[]
and copy the int[]
elements into it:
int[] myIntArray = ...;
Integer[] myIntegerArray = new Integer[myIntArray.length];
for (int i = 0; i < myIntArray.length; i++)
myIntegerArray[i] = myIntArray[i]; // autoboxing takes care of conversion
How can I sort an array using a custom comparator?
Your comparison function A::cmp
is a non-static member of A
. Thus, it takes three arguments: in addition to the two arguments explicitly declared, it also takes a pointer to A
to become the implicitly available this
. It also has a different type than normal function pointers: bool (A::)(int, int)
which decays into bool (A::*)(int, int)
when being passed by value.
You could std::bind()
your function to a suitable object, however:
std::sort(vec.begin(), vec.end(),
std::bind(&A::cmp, this, std::placeholders::_1, std::placeholders::_2));
Java Custom Comparator for sorting array of strings
What about using your Comparator with something like Selection Sort?
public class Test {
public static void main(String args[]) {
String arr[]={"zpppz","poop","zllo","bob","yea"};
Comparator<String> comparator = new Comparator<>() {
public int compare(String a, String b) {
if ((a.charAt(0) == a.charAt(a.length() - 1)) && (b.charAt(0) == b.charAt(b.length() - 1))) {
return a.compareTo(b);
}
return 0;
}
};
selectionSort(arr, comparator);
}
static <T> void selectionSort(T[] a, Comparator<T> c) {
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
if (c.compare(a[i], a[j]) > 0) {
T hold = a[i];
a[i] = a[j];
a[j] = hold;
}
}
}
}
}
result: [bob, poop, zllo, zpppz, yea]
Arrays.sort() is not accepting the comparator type object
Signature of method is: public static <T> void sort(T[] a, Comparator<? super T> c)
so the first argument is generic and you cannot put there primitive type that's why you get an error. For such sorting you have predefined sort method which can take primitive arrays
Java Comparator class to sort arrays
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
Related Topics
Java Date Parsing with Microsecond or Nanosecond Accuracy
Why Equals() Method When We Have == Operator
Why Were Applets Deprecated in Jdk 9
Java Annotations Values Provided in Dynamic Manner
Can't Find a Way to Color the Mandelbrot-Set the Way I'm Aiming For
How Do Hashcode() and Identityhashcode() Work at the Back End
How to Catch Out of Memory Exception in Java
How to Use "." as the Delimiter with String.Split() in Java
Java - How Would I Dynamically Add Swing Component to Gui on Click
Why Do I Get Java.Lang.Abstractmethoderror When Trying to Load a Blob in the Db
Why Can Java Collections Not Directly Store Primitives Types
Custom Button Not Working on MAC (Buttonui)
Bypass Generatedvalue in Hibernate (Merge Data Not in Db)
What's the Advantage of a Java Enum Versus a Class with Public Static Final Fields