constalgorithm = (n) => { let count = 0; const a = 100; for (const i in n) { for (const j in a) { count += 1; } } return count; } // 时间复杂度是o(N),一直一层循环是与输入有关
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 冒泡排序 constbubbleSort = (nums) => { const n = nums.length; for (const i in n - 1) { for (const j in n - i - i) { if (nums[j] > nums[j + 1]) { cache = nums[j] nums[j] = nums[j + 1] nums[j + 1] = cache } } } return nums; } // 时间复杂度是O(N^2),第一层复杂的o(N), 第二层平均循环次数为N/2,复杂度也为o(N)
1 2 3 4 5 6 7 8
// 递归 constalgorithm = (n) => { if (n <= 0) return1 const a = algorithm(n - 1) const b = algorithm(n - 1) return a + b; } // 时间复杂度是O(2^N)
1 2 3 4 5 6 7 8 9 10
// 递归 constalgorithm = (n) => { if (n <= 0) return1 let count = 0 for (const i in n) { count = algorithm(n - 1) } return count; } // 时间复杂度是O(N!)
1 2 3 4 5 6 7 8 9 10 11
// 一分为二,二分查找 constalgorithm = (n) => { let count = 0 let i = n while (i > 1) { i = i / 2 count += 1 } return count } // 时间复杂度是O(logN)
1 2 3 4 5 6 7 8 9 10
// 线性对数常出现在排序算法中,快速排序、归并排序、堆排序 constalgorithm = (n) => { let count = 0 let i = n while (i > 1) { i = i / 2 for (const j in n) count += 1 } } // 时间复杂度是O(NlogN)
空间复杂度的相关demo
1 2 3 4 5 6
constchild = () => 0
constparent = (n) => { for (const i in n) child() } // 空间复杂度o(1),因为栈帧空间被释放掉了,每次掉用child()后