I am trying to find out the run-time complexity of this algorithm.
public static void main(String[] args) throws InterruptedException{
for (int N=100; N<=1000000; N=N*5) {
long start = System.currentTimeMillis();
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= Math.pow(N,1.5); j++) {
i = i*2;
j = j*2;
Thread.sleep(10);
}
}
long stop = System.currentTimeMillis();
long elapsed = (long)(stop - start);
System.out.println();
System.out.println("For N=" + N + " RT in msec: "+elapsed);
}
}
The first for loop:
for (int N=100; N<=1000000; N=N*5) // runs n/5 times, so O(n).
The first inner loop:
for (int i = 1; i <= N; i++) // runs n times.
The second inner loop:
for (int j = 1; j <= Math.pow(N,1.5); j++) { // we can consider Math.pow O(1)
i = i*2;
j = j*2;
Thread.sleep(10);
}
So by multiplying all O(n) * O(n) * O(1) = O(n^2) Is my answer correct? I am a little confused on this. Will appreciate any clarification on this. Thank You
The first loop is actually O(k)
which 5^k = N
. Hence, k = log_5(N)
. The first inner loop is true (in O(n)
). And the second inner loop j
is each time is times to 2
. Hence, it is O(h)
which 2^h = N^1.5
. Therefore, h = 1.5 log(N)
.
In sum, the algorithm is in O(log_5(N) * N * log(N)) = O(N log^2(N))
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.