kotlin实现排序算法
时间: 2023-11-23 08:07:54 浏览: 90
排序算法实现
4星 · 用户满意度95%
Kotlin可以实现各种类型的排序算法,比如插入排序、冒泡排序、快速排序等等。以下是快速排序的Kotlin实现示例:
```kotlin
fun quickSort(list: MutableList<Int>, low: Int, high: Int) {
if (low >= high) return
val m = partition(list, low, high)
quickSort(list, low, m - 1)
quickSort(list, m + 1, high)
}
fun partition(list: MutableList<Int>, low: Int, high: Int): Int {
var i = low
var j = high + 1
val pivot = list[low]
while (true) {
while (list[++i] < pivot) if (i == high) break
while (list[--j] > pivot) if (j == low) break
if (i >= j) break
swap(list, i, j)
}
swap(list, low, j)
return j
}
fun swap(list: MutableList<Int>, i: Int, j: Int) {
val temp = list[i]
list[i] = list[j]
list[j] = temp
}
```
使用示例:
```kotlin
fun main() {
val list = mutableListOf(4, 2, 8, 1, 3, 9, 7, 6, 5)
quickSort(list, 0, list.size - 1)
println(list)
}
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9]
阅读全文