这个算法是 O(n 2 ),但是它在不到一秒的时间内运行。为什么这么快?
public class ScalabilityTest {
public static void main(String[] args) {
long oldTime = System.currentTimeMillis();
double[] array = new double[5000000];
for ( int i = 0; i < array.length; i++ ) {
for ( int j = 0; j < i; j++ ) {
double x = array[j] + array[i];
}
}
System.out.println( (System.currentTimeMillis()-oldTime) / 1000 );
}
}
编辑:
我将代码修改为以下内容,现在运行速度非常慢。
public class ScalabilityTest {
public static void main(String[] args) {
long oldTime = System.currentTimeMillis();
double[] array = new double[100000];
int p = 2;
int m = 2;
for ( int i = 0; i < array.length; i++ ) {
p += p * 12348;
for ( int j = 0; j < i; j++ ) {
double x = array[j] + array[i];
m += m * 12381923;
}
}
System.out.println( (System.currentTimeMillis()-oldTime) / 1000 );
System.out.println( p + ", " + m );
}
}