Question 1: Is this in O(n)?
That's correct (here, n
denotes the length of each of the two arrays).
Does it matter how many loops (not nested loops) are in method1?
It doesn't, as long as the number of loops is fixed, and the number of iterations in each loop is linear in n
. More formally, if C
is some constant, C*n
is O(n)
.
Question 2: What if there is a Arrays.sort(a);
Sorting is usually O(n logn)
, and this is what Arrays.sort(int[])
does on average. The documentation is vague about the worst-case performance:
This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.
This clearly stops short of guaranteeing O(n logn)
in the worst case. Reading between the lines suggests that it's probably O(n^2)
.
It is interesting to note that in JDK7, Arrays.sort(Object[])
uses a different algorithm to the one used by Arrays.sort(int[])
. The former is an adaptation of TimSort, and should therefore guarantee O(n logn)
worst-case performance. Unfortunately, the documentation again stop short of spelling this out.