15
Katupel
8y

In a programming exam, we had to write a program in 60 minutes, part of which was sorting some strings by length (strings the same length had to be in the same line)... I had like 3 minutes left, so i wrote this beauty:

boolean b = false;
for(int i = 0; i <= 999999; i++){
for(int j = 0; j <= strings.length; j++){
if(i == strings[j].length()){
System.out.print(s + " ");
b = true;
}
}
if(b){
System.out.println();
b = false;
}
}

Comments
  • 2
    O(999999*N). Some would say it's an O(N) solution. 😂
  • 0
    @sande Given the nested for, I'd say it's O(n^2)
  • 3
    @apex Though the actual solution would've been O(n^2)(or O(n*log(n)) , this code is O(n) since O(c*n) =O(n). Just a very very bad O(n).
  • 1
    @apex technically, he's right... Since the outer loop doesn't grow with the number of strings, it's essentially a constant. It's not trivial, but it's true.
  • 0
    I think I overlooked the fixed out cycle 😅
  • 1
    I feel like this is still technically Theta(n^2), because it only works if n<=c where c is the constant, right? So c*n would have to be at least n*n, which makes c no longer constant because it would have to get infinitely large as the length of the string gets infinitely large
Add Comment