for (int i = 0; i < N; i ++) print(i);Answer: O(N)
for (int i = 0; i < N/2; i ++) print(i);Answer: O(N)
for (int i = 0; i < N; i ++) for (int j = 0; j < N/2; j++) print(i);Answer: O(N2)
for (int i = 0; i < N; i ++) for (int j = 0; j < i; j++) print(i);Answer: O(N2)
for (int i = 0; i < N; i ++) for (int j = 0; j < 5; j++) print(i);Answer: O(N)
for (int i = 1; i < N/2; i*=2) print(i);Answer: O(log(N))
for (int i = N; i > 1; i/=2) print(i);Answer: O(log(N))
for (int i = N; i > N-5; i--) print(i);O(1)
If a is N x N (square), what is the complexity of this code?
Answer:
int numRows = a.length; int numCols = a[0].length; //first row for (int col=0; col<numCols; col++) System.out.println(a[0][col]); //last row for (int col=0; col<numCols; col++) System.out.println(a[numRows-1][col]); //first col for (int row=0; row<numRows; row++) System.out.println(a[row][0]); //first row for (int row=0; row<numRows; row++) System.out.println(a[row][numCols-1]); Complexity is O(N).
//one-dimensional array int count = 0; for (int index = 0; index < a.length; index++) if (a[index] == x) count++; //two-dimensional array int count = 0; for (int row = 0; row < a.length; row++) for (int col = 0; col < a[0].length; col++) if (a[row][col] == x) count++;
int[] a = new int[51]; //automatically inits to all 0 //instead of for loop, could use while that stops //when read sentinel (eg, a number not in -25..+25) for (int i = 0; i < N; i ++) { int num = Keyboard.readInt(); a[num+25]++; }
Square[] squares = new Square[10]; for (int i = 0; i < 10; i++) { squares[i] = new Square(); square[i].printSquare(); //or could print in separate loop }