+ 1
Which sorting algorithm is being used in Collections for integer arrays?
Is it a quick sort or something else? Is there a way to control the sorting logic?
3 Answers
+ 6
'[...] The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. [...]'
See
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)
+ 2
Hi, I m noto a Java expert,but... Collections by themselves don't have a predefined order. You can convert them to a java.util.List. Then you can use one form of java.util.Collections.sort
Collection< T > collection = ...;
List< T > list = new ArrayList< T >( collection ); Collections.sort( list ) ;
+ 2
You can pass your own sorting algorithm as the second argument to the sort function.
sort(myList, new Comparator<T>() {
// This method needs to return -1(or a negative number), 0, or 1(or a positive number)
int compare(T a, T b) {
if (a == b ) { return 0; }
if ( a < b ) { return -1; }
if ( a > b ) { return 1; }
}
});