I want to know the complexity of this algorithm. In my case both in good, medium and worst is O(n^2)
public char getModa(char[] a){
int ii[] =new int[a.length];
char[] t= new char[a.length];
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++){
if(a[j]==a[i]){
ii[i]++;
t[i]=a[j];
}
}
}
int cc=0;
for(int i=0;i<ii.length;i++){
if(ii[i]>ii[cc]) cc=i;
}
return a[cc];
}
The complexity of all cases (best/average/worst) is
O(n^2), the bottle-neck is the double iteration over(i,j)inrange([0,a.length),[0,a.length)).To clarify why it is indeed
O(n^2)and notO(n^3)as one might think – because the last loop is not ‘nested’ in side the bottle-neck, so the complexity of the 3 loops is basicallyO(n^2+n), but sinceO(n^2+n) = O(n^2), this is the answer.In fact – there is no variation at all, for the same length arrays – the algorithm has the same number of iterations, regardless of what the input exactly is.