fun main() {
var values = intArrayOf(3, 1, 2)
var i = 1
while (i < 3) {
var key = values[i]
var j = i - 1
while ((j >= 0) && (values[j] > key)) {
values[j + 1] = values[j]
j -= 1
}
values[j + 1] = key
i += 1
}
i = 0
while (i < 3) {
println(values[i])
i += 1
}
}
输出
1
2
3
生活中的例子
插入一张新的号码牌
工作人员把 2、5、8 号票按顺序摆好了。6 号票应该放在哪里?
初始状态2 5 8 +6
结果2 5 6 8
把8向右挪一位。5后面空出来的位置就是插入点。
添加上午的预约
记事本上已有10点和12点的预约,再加一个9点的预约。
初始状态10 12 +9
结果9 10 12
原有的两个预约都比较晚,各向后移一格就能腾出位置。
在末尾补记一笔付款
按日期排序的账本最后两笔是4日和6日的记录。现在收到7日的付款,哪些记录要挪动?
初始状态4 6 +7
结果4 6 7
原有的最后一个日期就在7日之前。直接追加到末尾,其余记录不用挪。
开销与局限
插入排序适合较短或接近有序的列表。完全逆序时,需要O(n²)次移动和比较。
时间复杂度
最好情况: Θ(n)
平均情况: Θ(n²)
最坏情况: Θ(n²)
用 Kotlin 实现插入排序
Kotlin 源代码
fun insertionSort(arr: IntArray) {
val lastIndex: Int = arr.size - 1
for (i in 1..lastIndex) {
val temp: Int = arr[i]
var holePosition: Int = i
while(holePosition > 0 && arr[holePosition - 1] > temp) {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
arr[holePosition] = temp
}
}
fun printArray(arr: IntArray) {
val lastIndex: Int = arr.size - 1;
for (i in 0..lastIndex) {
val num = arr[i]
print("$num ")
}
println("")
}
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(15, 3, 12, 6, -9, 9, 0);
print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
print("After Sorting: ")
printArray(arr)
}
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
广告
一步步看例子
从 [15, 3, 12, 6, -9, 9, 0] 开始。
先把 15 当作已经排好序的部分,把下一个值 3 暂时存起来。
把15向右移一位,在开头插入3。现在排好序的前段是[3, 15]。
依次处理余下的每个值,插入前只移动比它大的值。相等的值仍按原来的先后顺序排列。
用 Kotlin 实现插入排序:逐步讲解
Kotlin 源代码
fun insertionSort(arr: IntArray) {
val lastIndex: Int = arr.size - 1
// Un-sorted array from position 1 to size -1
for (i in 1..lastIndex) {
// Take the left most item in an un-sorted array to temp variable
val temp: Int = arr[i]
// Mark the left most position as empty or hole
var holePosition: Int = i
// Traverse the sorted array from right to left direction
// Move the item from the sorted array to the empty position (i.e. holePosition) only if the temp variable is less then
// Mark the current item's position as empty by decrementing the value by one
while(holePosition > 0 && arr[holePosition - 1] > temp) {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
// Once the comparison done, move the value in temp variable to the lastly marked empty position
arr[holePosition] = temp
}
}
fun printArray(arr: IntArray) {
val lastIndex: Int = arr.size - 1;
// Loop the item and print each item in the console with white space seperated
for (i in 0..lastIndex) {
val num = arr[i]
print("$num ")
}
println("")
}
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(15, 3, 12, 6, -9, 9, 0);
print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
print("After Sorting: ")
printArray(arr)
}
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15