Skip to content

Instantly share code, notes, and snippets.

@ok3141
Created January 9, 2020 23:40
Show Gist options
  • Save ok3141/6b1d7610ee3d8ab0f6f416270767a174 to your computer and use it in GitHub Desktop.
Save ok3141/6b1d7610ee3d8ab0f6f416270767a174 to your computer and use it in GitHub Desktop.
public class Complexity {
public static void main(String[] args) {
int n = 100_000;
int[] a = new int[n];
java.util.Random r = new java.util.Random();
for (int i = 0; i < n; ++i) {
a[i] = r.nextInt();
}
System.out.println("n = " + n);
long s, e;
s = System.currentTimeMillis();
int x1 = 0;
for (int i = 0; i < n; ++i) {
x1 += a[i];
}
e = System.currentTimeMillis();
System.out.println("O(n) = " + (e - s) + " ms");
int m = log2(n);
s = System.currentTimeMillis();
int x2 = 0;
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
x2 += a[i];
}
}
e = System.currentTimeMillis();
System.out.println("O(n * log(2, n)) = " + (e - s) + " ms");
s = System.currentTimeMillis();
int x3 = 0;
for (int j = 0; j < n; ++j) {
for (int i = 0; i < n; ++i) {
x3 += a[i];
}
}
e = System.currentTimeMillis();
System.out.println("O(n * n) = " + (e - s) + " ms");
System.out.println("X = " + Integer.toHexString(x1 + x2 + x3));
}
public static int log2(int n) {
if (n <= 0) throw new IllegalArgumentException();
return 31 - Integer.numberOfLeadingZeros(n);
}
}
@ok3141
Copy link
Author

ok3141 commented Jan 9, 2020

n = 100000
O(n) = 4 ms
O(n * log(2, n)) = 6 ms
O(n * n) = 3530 ms
X = 1fa29f4c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment