classBubbleSort{ funsort(nums: IntArray) { val n = nums.size for (i in0 until n) { // nums[0, n - 1 - i]是无序区域,初始时整个数组无序 // nums[n - i,n - 1]是有序区域,是数组中大的数
// 记录一趟冒泡是否有交换发生 var isNotSwapped = true
// 因为要比较当前和下一个数大小,所以j只能取到n - 1 - i的前一个数 for (j in0 until n - 1 - i) { // 不是升序,就要交换一下 if (nums[j] > nums[j + 1]) { // 交换 val tmp = nums[j + 1] nums[j + 1] = nums[j] nums[j] = tmp // 标记有交换 isNotSwapped = false } }
// 没有交换,说明无序区域已经有序,那么整个数组也是有序的了 if (isNotSwapped) break } } }
classSelectionSort{ funsort(nums: IntArray) { val n = nums.size for (i in0 until n) { // s[0,i-1]为已排序区域,s[i,n-1]为未排序区域 // 从未排序取一个最小的放入已排序区域的末尾 var minIndex = i for (j in i + 1 until n) { if (nums[j] < nums[minIndex]) { minIndex = j } } // 将未排序区域中最小值与已排序区域末尾的下一个位置的数字交换 // 已排序区域末尾的下一个位置就是i了,最小值索引是minIndex val tmp = nums[minIndex] nums[minIndex] = nums[i] nums[i] = tmp } } }
classShellSort{ funsort(nums: IntArray) { val n = nums.size var d = 1 while (d < n / 3) { d = 3 * d + 1 } while (d >= 1) { for (i in d until n) { for (j in i downTo d step d) { if (nums[j] < nums[j - d]) { val tmp = nums[j] nums[j] = nums[j - d] nums[j - d] = tmp break } } } d /= 3 } } }
/** * [nums]取值范围在1到w */ funsort(nums: IntArray) { val n = nums.size val copied = nums.copyOf() val count = IntArray(w + 1) { 0 } // 统计每个取值有多少个 for (num in nums) { count[num]++ } // 累加计数 for (i in1..w) { count[i] += count[i - 1] } // 逆序遍历原数组,保持元素相对顺序不变 for (i in n - 1 downTo 0) { val index = count[copied[i]] - 1 nums[index] = copied[i] count[copied[i]]-- } } }
使用广泛。ACRA is used in 1.57% (See AppBrain/stats) of all apps on Google Play as of June 2020. That’s over 13 thousand apps and over 5 billion downloads including ACRA.
Kotlin 只是把 extends 换成了 : 冒号。 class Monster<T : Animal> 设置多个边界可以使用 where 关键字: class Monster<T> where T : Animal, T : Food 有人在看文档的时候觉得这个 where 是个新东西,其实虽然 Java 里没有 where ,但它并没有带来新功能,只是把一个老功能换了个新写法。
不过笔者觉得 Kotlin 里 where 这样的写法可读性更符合英文里的语法,尤其是如果 Monster 本身还有继承的时候:
1 2
classMonster<T> : MonsterParent<T> where T : Animal