时间复杂度计算

围巾🧣 2020年07月18日 685次浏览

复杂度排序

O(1) < O(logn) < O(n) < O(nlogn) < O(n^2) < O(n^3) < O(2^n) < O(n!) < O(n^n)

实例分析

  1. public static void test1(int n) {
  2. // 汇编指令

  3. // 1
  4. if (n > 10) {
  5. System.out.println("n > 10");
  6. } else if (n > 5) { // 2
  7. System.out.println("n > 5");
  8. } else {
  9. System.out.println("n <= 5");
  10. }

  11. // 1 + 4 + 4 + 4
  12. for (int i = 0; i < 4; i++) {
  13. System.out.println("test");
  14. }

  15. // O(1)
  16. // O(1)
  17. }

  18. public static void test2(int n) {
  19. // O(n)
  20. // 1 + 3n
  21. for (int i = 0; i < n; i++) {
  22. System.out.println("test");
  23. }
  24. }

  25. public static void test3(int n) {
  26. // 1 + 2n + n * (1 + 3n)
  27. // 1 + 2n + n + 3n^2
  28. // 3n^2 + 3n + 1
  29. // O(n^2)

  30. // O(n)
  31. for (int i = 0; i < n; i++) {
  32. for (int j = 0; j < n; j++) {
  33. System.out.println("test");
  34. }
  35. }
  36. }

  37. public static void test4(int n) {
  38. // 1 + 2n + n * (1 + 45)
  39. // 1 + 2n + 46n
  40. // 48n + 1
  41. // O(n)
  42. for (int i = 0; i < n; i++) {
  43. for (int j = 0; j < 15; j++) {
  44. System.out.println("test");
  45. }
  46. }
  47. }

  48. public static void test5(int n) {
  49. // 8 = 2^3
  50. // 16 = 2^4

  51. // 3 = log2(8)
  52. // 4 = log2(16)

  53. // 执行次数 = log2(n)
  54. // O(logn)
  55. while ((n = n / 2) > 0) {
  56. System.out.println("test");
  57. }
  58. }

  59. public static void test6(int n) {
  60. // log5(n)
  61. // O(logn)
  62. while ((n = n / 5) > 0) {
  63. System.out.println("test");
  64. }
  65. }

  66. public static void test7(int n) {
  67. // 1 + 2*log2(n) + log2(n) * (1 + 3n)

  68. // 1 + 3*log2(n) + 2 * nlog2(n)
  69. // O(nlogn)
  70. for (int i = 1; i < n; i = i * 2) {
  71. // 1 + 3n
  72. for (int j = 0; j < n; j++) {
  73. System.out.println("test");
  74. }
  75. }
  76. }

  77. public static void test10(int n) {
  78. // O(n)
  79. int a = 10;
  80. int b = 20;
  81. int c = a + b;
  82. int[] array = new int[n];
  83. for (int i = 0; i < array.length; i++) {
  84. System.out.println(array[i] + c);
  85. }
  86. }