+ 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?

16th Feb 2017, 9:36 PM
Vlad Dor
Vlad Dor - avatar
3 Respostas
+ 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)
16th Feb 2017, 11:36 PM
Tashi N
Tashi N - avatar
+ 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 ) ;
16th Feb 2017, 11:33 PM
Nifriz
Nifriz - avatar
+ 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; } } });
17th Feb 2017, 2:55 AM
ChaoticDawg
ChaoticDawg - avatar