We all know about sorting, sorting is one of the most complex and common operations used. The discussion here is dedicated understand more on what are different types of different sorting algorithms are used java in the internal Collections and Arrays. As we all know Java provides two builtin ways to do sorting:
1. Using the Arrays.sort method on an array.
2. Using the Collections.sort method on the collection of object such as a List.
how the above can be used
Arrays.sort(A);
Arrays.sort(A, fromIndex, toIndex);
The Arrays.sort function also gives the ability to sort a range between two indices. The "toIndex" argument name is misleading since the sort range is really between fromIndex and toIndex – 1, inclusive. Thus these two calls are equivalent
For a list, L, of Comparable elements, this is defined:
Collections.sort(L);
When no Comparator object is passed to a sort algorithm, sorting is done using the "natural order" of supposedly Comparable elements as defined by the compareTo function. The Collections.sort does a type-check that the elements are Comparable, but Arrays.sort can only do a run-time check. All other sorting is done using a Comparator object comparator passed to the sort function. Here are the relevant calls:
Arrays.sort(A, comparator);
Arrays.sort(A, fromIndex, toIndex, cmp);
Collections.sort(L, comparator);
After doing some introspection on the source code of of java Collections and Arrays, I was able to figure out that java uses some kind of advance tuned version of Merge Sort ,Quick Sort algorithms and insertion sort too.
Mostly java uses the Merge Sort and Quick Sort that depends on what kind of data is passed for sorting It can be a primitive type or objects. It also uses Insertion Sort when the elements are fewer and less than 7.
In Java 7 TimSort was introduced which was the replacement for the MergeSort algorithm. With Java 8 yet to be released we have ParallelSort coming soon.
We will go over the code snippet of all the algorithms discussed above and try to get some info about the parallelSort also.
Code snippet coming soon.....
Mostly java uses the Merge Sort and Quick Sort that depends on what kind of data is passed for sorting It can be a primitive type or objects. It also uses Insertion Sort when the elements are fewer and less than 7.
In Java 7 TimSort was introduced which was the replacement for the MergeSort algorithm. With Java 8 yet to be released we have ParallelSort coming soon.
We will go over the code snippet of all the algorithms discussed above and try to get some info about the parallelSort also.
Code snippet coming soon.....