/** * File: time_complexity.kt * Created Time: 2024-01-25 * Author: curtishd (1023632660@qq.com) */ package chapter_computational_complexity.time_complexity /* 常数阶 */ fun constant(n: Int): Int { var count = 0 val size = 10_0000 for (i in 0.. nums[j + 1]) { // 交换 nums[j] 与 nums[j + 1] nums[j] = nums[j + 1].also { nums[j + 1] = nums[j] } count += 3 // 元素交换包含 3 个单元操作 } } } return count } /* 指数阶(循环实现) */ fun exponential(n: Int): Int { var count = 0 // 细胞每轮一分为二,形成数列 1, 2, 4, 8, ..., 2^(n-1) var base = 1 for (i in 0.. 1) { n1 /= 2 count++ } return count } /* 对数阶(递归实现) */ fun logRecur(n: Int): Int { if (n <= 1) return 0 return logRecur(n / 2) + 1 } /* 线性对数阶 */ fun linearLogRecur(n: Int): Int { if (n <= 1) return 1 var count = linearLogRecur(n / 2) + linearLogRecur(n / 2) for (i in 0..