In: Computer Science
class Main {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
//Complexity Analysis
//Instructions: Print the time complexity of method Q1_3 with
respect to n=Size of input array. For example, if the complexity of
the
//algorithm is Big O nlogn, add the following code where specified:
System.out.println("O(nlogn)");
//TODO
}
public static void Q1_3(int[] array){
int count = 0;
for(int i = 0; i < array.length; i++){
for(int j = i; j < array.length; j++){
for(int k = j; k < array.length; k++){
count++;
}
}
}
}
}
Time Complexity: Since there are three nested loops in the Q1_3 menthod and in each loop each iterators i,j,k are gettubg incremented by one unit only. So the overall time complexity in big O notation will O(n^3).
Have a look at the below code.
class Main {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
Q1_3(array);
}
public static void Q1_3(int[] array){
int count = 0;
for(int i = 0; i < array.length; i++){
for(int j = i; j < array.length; j++){
for(int k = j; k < array.length; k++){
count++;
}
}
}
System.out.println("O(n^3)");
}
}
Happy Learning!