MCPcopy Create free account
hub / github.com/algorithmzuo/algorithm-journey / main

Method main

src/class007/Complexity.java:34–99  ·  view source on GitHub ↗
(String[] args)

Source from the content-addressed store, hash-verified

32 }
33
34 public static void main(String[] args) {
35 // 随机生成长度为n
36 // 值在0~v-1之间
37 // 且任意相邻两数不相等的数组
38 int n = 10;
39 int v = 4;
40 int[] arr1 = new int[n];
41 arr1[0] = (int) (Math.random() * v);
42 for (int i = 1; i < n; i++) {
43 do {
44 arr1[i] = (int) (Math.random() * v);
45 } while (arr1[i] == arr1[i - 1]);
46 }
47 for (int num : arr1) {
48 System.out.print(num + " ");
49 }
50 System.out.println();
51 System.out.println("=========");
52
53 // java中的动态数组是ArrayList
54 // 各个语言中的动态数组的初始大小和实际扩容因子可能会变化,但是均摊都是O(1)
55 // 课上用2作为扩容因子只是举例而已
56 ArrayList<Integer> arr2 = new ArrayList<>();
57 arr2.add(5); // 0
58 arr2.add(4); // 1
59 arr2.add(9); // 2
60 arr2.set(1, 6); // arr[1]由4改成了6
61 System.out.println(arr2.get(1));
62 System.out.println("=========");
63
64 int[] arr = { 64, 31, 78, 0, 5, 7, 103 };
65 bubbleSort(arr);
66 for (int num : arr) {
67 System.out.print(num + " ");
68 }
69 System.out.println();
70 System.out.println("=========");
71
72 int N = 200000;
73 long start;
74 long end;
75 System.out.println("测试开始");
76 start = System.currentTimeMillis();
77 for (int i = 1; i <= N; i++) {
78 for (int j = i; j <= N; j += i) {
79 // 这两个嵌套for循环的流程,时间复杂度为O(N * logN)
80 // 1/1 + 1/2 + 1/3 + 1/4 + 1/5 + ... + 1/n,也叫"调和级数",收敛于O(logN)
81 // 所以如果一个流程的表达式 : n/1 + n/2 + n/3 + ... + n/n
82 // 那么这个流程时间复杂度O(N * logN)
83 }
84 }
85 end = System.currentTimeMillis();
86 System.out.println("测试结束,运行时间 : " + (end - start) + " 毫秒");
87
88 System.out.println("测试开始");
89 start = System.currentTimeMillis();
90 for (int i = 1; i <= N; i++) {
91 for (int j = i; j <= N; j++) {

Callers

nothing calls this directly

Calls 7

bubbleSortMethod · 0.95
randomMethod · 0.45
printMethod · 0.45
printlnMethod · 0.45
addMethod · 0.45
setMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected