0

How can I calculate the time complexity of this program? Is there a more efficient solution?

public class MinJumpstoEnd {
    public static void main(String[] args) {
        
        int[] a = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
        //i is used for array elements & c to count jumps

        int i =0,c =0;
        int j = a[0];
        
        while(a.length-i > j) {
            if(a[i]==0) {
                System.out.println("Cant Reach");
            }

            i += j;
            c+=1;

            j = a[i]-1;
            System.out.println("j:"+j);
        }
        System.out.println("Jumps : "+c);
    }
}
trincot
  • 317,000
  • 35
  • 244
  • 286

1 Answers1

0

In the worst case your i has to traverse the whole array, and hence it would be O(n). It might happen that it might skip few elements in between while traversing but still it would be a linear function.

  • I don't think this answers OP's question (at least not in detail). They are asking how to calculate it, and not which complexity measurements apply to which types of algorithms. Though that helps, it may not be obvious to them how to connect the dots. – ryanwebjackson Aug 08 '21 at 20:44