/** * 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..