Given a sorted array in descending order, following code counts pairs of two elements with the difference d. It is easy to give an O(n2) bound for the time complexity of the function countingDifference in below codes; n times in outer for-loop and n times inner while-loop.
But a more careful analysis shows that in fact we can give an O(2n) = O(n) bound on the time complexity of this functions. The command j++; is executed no more than n times totally, while outer for-loop is looping n times. So, time complexity of this function is O(n+n) = O(2n) = O(n).
The statement 'this function(algorithm) is O(n2)' is still right. 'this algorithm is O(n)' gives more information about the function.
But a more careful analysis shows that in fact we can give an O(2n) = O(n) bound on the time complexity of this functions. The command j++; is executed no more than n times totally, while outer for-loop is looping n times. So, time complexity of this function is O(n+n) = O(2n) = O(n).
The statement 'this function(algorithm) is O(n2)' is still right. 'this algorithm is O(n)' gives more information about the function.
public class CodeTest {
static int counter1 =0;
static int counter2 =0;
public static void main(String[] args) {
int input[] = {112, 39, 34, 32, 30, 27, 12, 11, 9, 8, 5, 2, 0};
int d = 2;
System.out.print("Input: ");
for(int i = 0; i<input.length;i++)
System.out.print(input[i] + " ");
System.out.println();
System.out.println( "For " + input.length + " -length array: " + countDiffernce(input, d) + " pairs are " + d + "-differences " );
System.out.println ("Outer Loop: " + counter1 + " times, Inner Loop: " + counter2 + " times");
}
public static int countDiffernce(int input[], int d) {
int cnt =0, n = input.length;
int j = 1;
for (int i = 0; i < n && j < n; i++) {
counter1++;
while ( (j < n-1) && (input[i] - input[j] < d)) {
counter2++;
j++;
}
if(input[i] - input[j] == d) {
cnt++;
System.out.println("\t" + input[i] + " - " + input[j] + " = " + d);
}
}
return cnt;
}
}
static int counter1 =0;
static int counter2 =0;
public static void main(String[] args) {
int input[] = {112, 39, 34, 32, 30, 27, 12, 11, 9, 8, 5, 2, 0};
int d = 2;
System.out.print("Input: ");
for(int i = 0; i<input.length;i++)
System.out.print(input[i] + " ");
System.out.println();
System.out.println( "For " + input.length + " -length array: " + countDiffernce(input, d) + " pairs are " + d + "-differences " );
System.out.println ("Outer Loop: " + counter1 + " times, Inner Loop: " + counter2 + " times");
}
public static int countDiffernce(int input[], int d) {
int cnt =0, n = input.length;
int j = 1;
for (int i = 0; i < n && j < n; i++) {
counter1++;
while ( (j < n-1) && (input[i] - input[j] < d)) {
counter2++;
j++;
}
if(input[i] - input[j] == d) {
cnt++;
System.out.println("\t" + input[i] + " - " + input[j] + " = " + d);
}
}
return cnt;
}
}
Computation Complexity - Double Loop