mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 02:26:29 +08:00
merge codes
This commit is contained in:
commit
35d4208fa8
3 changed files with 49 additions and 1 deletions
19
codes/go/chapter_sorting/insertion_sort/insertion_sort.go
Normal file
19
codes/go/chapter_sorting/insertion_sort/insertion_sort.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
//File: insertion_sort.go
|
||||
//Created Time: 2022-12-12
|
||||
//Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package insertion_sort
|
||||
|
||||
func insertionSort(nums []int) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for i := 1; i < len(nums); i++ {
|
||||
base := nums[i]
|
||||
j := i - 1
|
||||
// 内循环:将 base 插入到左边的正确位置
|
||||
for j >= 0 && nums[j] > base {
|
||||
nums[j+1] = nums[j] // 1. 将 nums[j] 向右移动一位
|
||||
j--
|
||||
}
|
||||
nums[j+1] = base // 2. 将 base 赋值到正确位置
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
//File: insertion_sort_test.go
|
||||
//Created Time: 2022-12-12
|
||||
//Author: msk397 (machangxinq@gmail.com)
|
||||
|
||||
package insertion_sort
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInsertionSort(t *testing.T) {
|
||||
nums := []int{4, 1, 3, 1, 5, 2}
|
||||
insertionSort(nums)
|
||||
fmt.Println("插入排序完成后 nums = ", nums)
|
||||
}
|
|
@ -79,7 +79,20 @@ comments: true
|
|||
=== "Go"
|
||||
|
||||
```go title="insertion_sort.go"
|
||||
|
||||
/* 插入排序 */
|
||||
func insertionSort(nums []int) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for i := 1; i < len(nums); i++ {
|
||||
base := nums[i]
|
||||
j := i - 1
|
||||
// 内循环:将 base 插入到左边的正确位置
|
||||
for j >= 0 && nums[j] > base {
|
||||
nums[j+1] = nums[j] // 1. 将 nums[j] 向右移动一位
|
||||
j--
|
||||
}
|
||||
nums[j+1] = base // 2. 将 base 赋值到正确位置
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
|
|
Loading…
Reference in a new issue