I found that java.util.Arrays.sort(Object[]) use 2 kinds of sorting algorithms(in JDK 1.6).
pseudocode:
if(array.length<7)
insertionSort(array);
else
mergeSort(array);
Why does it need 2 kinds of sorting here? for efficiency?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s important to note that an algorithm that is
O(N log N)is not always faster in practice than anO(N^2)algorithm. It depends on the constants, and the range ofNinvolved. (Remember that asymptotic notation measures relative growth rate, not absolute speed).For small
N, insertion sort in fact does beat merge sort. It’s also faster for almost-sorted arrays.Here’s a quote:
Here’s another quote from Best sorting algorithm for nearly sorted lists paper:
What this means is that, in practice:
NconsideredRelated questions
A numerical example
Let’s consider these two functions:
f(x) = 2x^2; this function has a quadratic growth rate, i.e. "O(N^2)"g(x) = 10x; this function has a linear growth rate, i.e. "O(N)"Now let’s plot the two functions together:
Source: WolframAlpha:
plot 2x^2 and 10x for x from 0 to 10Note that between
x=0..5,f(x) <= g(x), but for any largerx,f(x)quickly outgrowsg(x).Analogously, if A1 is a quadratic algorithm with a low overhead, and A2 is a linear algorithm with a high overhead, for smaller input, A1 may be faster than A2.
Thus, you can, should you choose to do so, create a hybrid algorithm A3 which simply selects one of the two algorithms depending on the size of the input. Whether or not this is worth the effort depends on the actual parameters involved.
Many tests and comparisons of sorting algorithms have been made, and it was decided that because insertion sort beats merge sort for small arrays, it was worth it to implement both for
Arrays.sort.