I have a code that uses Arrays.sort(char[]) in the following manner:
void arrayAnalysis(String[] array){
for(int a=0; a<array.length;a++){
char[] letters = array[a].toCharArray();
Arrays.sort(letters);
...
for(int b=a+1; b<array.length;b++){
char[] letters2 = array[b].toCharArray();
Arrays.sort(letters2);
if(Arrays.equals(letters, letters2)
print("equal");
}
}
}
In this case, n is equal to the array size. Due to the nested for loops, performance is automatically O(n^2). However, I think Arrays.sort (with O(nlog(n))) also affects the performance and makes it worse than O(n^2). Is this thinking correct?
Would the final performance be O(n*nlog(n)*(n*nlog(n))? Or am I way off?
Thanks.
Edit: I should add that while n is related to the array size, Arrays.sort is working with the number of letters in the array element. That is part of my confusion if this should be added to the performance analysis.
Edit2: It would be cool if the down-voter left a comment as to why it was deemed as a bad question.
If
nis the length of the array, andmis the length of eacharray[i], then you will, on each ofn^2iterations, perform anO(m log m)sort, so overall it’sO(n^2 (m log m))(OrO(n^3 log n)ifn == m. [EDIT: now that I think more about this, your guess is right, and this is the wrong complexity. But what I say below is still correct!]]This is not really necessary, though. You could just make a sorted copy of the array, and do your nested for-loop using that one. Look at what happens when
ais 0: first you sortarray[0], then in the inner for loop you sortarray[1]througharray[n].Then when
ais 1, you first sortarray[1], then in the inner for looparray[2]througharray[n]. But you already sorted all that, and it’s not as if it will have changed in the interim.