-4

Optimize (Reduce the space and Time complexity)this function as much as possible.

  public void q1(String str, int[] arr)
  {    
        String local = "findnumber"; 
        for(int i=0; i<arr.length; i++)
        { 
            if(str.equals(local) && arr[i] * 2 > 10)
            { 
                Integer in = new Integer(arr[i]);    
                in = in * 2; 
                System.out.print(in.toString());
            } 
        } 
   } 
SimonC
  • 6,590
  • 1
  • 23
  • 40

1 Answers1

3

Looks like homework but I'll bite. Here's what I got...

  • str.equals(local) can be calculated outside the loop (and may stop you entering the loop at all)
  • You can store the value of arr[i] to stop it being looked up multiple times
  • Why create an Integer from i when you are just doing maths on it?
  • in *= 2 is theoretically faster than in = in * 2 (or i if you kill in as above)
  • Since all you ever use is arr[i] * 2, calculate that once and use it in the if as well as the output. (no need for the in=in*2 or in*=2 at all)
  • Buffer up the output and just have one output statement at the end of the loop.
John3136
  • 28,809
  • 4
  • 51
  • 69
  • `in` left shift is the same as `*2` – Steve Kuo Jun 04 '13 at 04:27
  • @SteveKuo true. Could even be faster (I haven't gone to that level in the JVM specs). I don't do it because a) I think it makes the code less readable/obvious and b) the difference between `i=i*2`, `i*=2` and `i<<2` doesn't often matter in the real world ;-) – John3136 Jun 04 '13 at 04:35
  • I don't see how any of these changes the complexity of anything. – R. Martinho Fernandes Jun 04 '13 at 10:25
  • @R.MartinhoFernandes the first 2 are about the same, `i<<2` is something (that in my experience) not everyone gets. People from a Comp Sci background get it but others with different backgrounds generally know it is a shift, but don't have that understanding of what it ends up doing. – John3136 Jun 04 '13 at 11:35