From 51a6f374a7e6cf4cbf290ab5bf0740ba7f9aa0e7 Mon Sep 17 00:00:00 2001 From: machangxin Date: Mon, 12 Dec 2022 18:32:58 +0800 Subject: [PATCH] Insertion sort using go --- .../insertion_sort/insertion_sort.go | 20 +++++++++++++++++++ .../insertion_sort/insertion_sort_test.go | 17 ++++++++++++++++ docs/chapter_sorting/insertion_sort.md | 14 +++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 codes/go/chapter_sorting/insertion_sort/insertion_sort.go create mode 100644 codes/go/chapter_sorting/insertion_sort/insertion_sort_test.go diff --git a/codes/go/chapter_sorting/insertion_sort/insertion_sort.go b/codes/go/chapter_sorting/insertion_sort/insertion_sort.go new file mode 100644 index 000000000..47effeb75 --- /dev/null +++ b/codes/go/chapter_sorting/insertion_sort/insertion_sort.go @@ -0,0 +1,20 @@ +/* + 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 赋值到正确位置 + } +} diff --git a/codes/go/chapter_sorting/insertion_sort/insertion_sort_test.go b/codes/go/chapter_sorting/insertion_sort/insertion_sort_test.go new file mode 100644 index 000000000..1b37d6862 --- /dev/null +++ b/codes/go/chapter_sorting/insertion_sort/insertion_sort_test.go @@ -0,0 +1,17 @@ +/* + 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) +} diff --git a/docs/chapter_sorting/insertion_sort.md b/docs/chapter_sorting/insertion_sort.md index 86debc625..6edf060f5 100644 --- a/docs/chapter_sorting/insertion_sort.md +++ b/docs/chapter_sorting/insertion_sort.md @@ -79,6 +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 赋值到正确位置 + } +} ```