Merge pull request #80 from Slone123c/patch

Bubble sort using go
This commit is contained in:
Yudong Jin 2022-12-07 21:32:41 +08:00 committed by GitHub
commit 97d016f37a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 89 additions and 2 deletions

View File

@ -0,0 +1,38 @@
// File: bubble_sort.go
// Created Time: 2022-12-06
// Author: Slone123c (274325721@qq.com)
package bubble_sort
/* 冒泡排序 */
func bubbleSort(nums []int) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i := len(nums) - 1; i > 0; i-- {
// 内循环:冒泡操作
for j := 0; j < i; j++ {
if nums[j] > nums[j+1] {
// 交换 nums[j] 与 nums[j + 1]
nums[j], nums[j+1] = nums[j+1], nums[j]
}
}
}
}
/* 冒泡排序(标志优化)*/
func bubbleSortWithFlag(nums []int) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i := len(nums) - 1; i > 0; i-- {
flag := false // 初始化标志位
// 内循环:冒泡操作
for j := 0; j < i; j++ {
if nums[j] > nums[j+1] {
// 交换 nums[j] 与 nums[j + 1]
nums[j], nums[j+1] = nums[j+1], nums[j]
flag = true // 记录交换元素
}
}
if flag == false { // 此轮冒泡未交换任何元素,直接跳出
break
}
}
}

View File

@ -0,0 +1,20 @@
// File: bubble_sort_test.go
// Created Time: 2022-12-06
// Author: Slone123c (274325721@qq.com)
package bubble_sort
import (
"fmt"
"testing"
)
func TestBubbleSort(t *testing.T) {
nums := []int{4, 1, 3, 1, 5, 2}
bubbleSort(nums)
fmt.Println("冒泡排序完成后 nums = ", nums)
nums1 := []int{4, 1, 3, 1, 5, 2}
bubbleSortWithFlag(nums1)
fmt.Println("冒泡排序完成后 nums1 = ", nums)
}

View File

@ -112,7 +112,19 @@ comments: true
=== "Go" === "Go"
```go title="bubble_sort.go" ```go title="bubble_sort.go"
/* 冒泡排序 */
func bubbleSort(nums []int) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i := len(nums) - 1; i > 0; i-- {
// 内循环:冒泡操作
for j := 0; j < i; j++ {
if nums[j] > nums[j+1] {
// 交换 nums[j] 与 nums[j + 1]
nums[j], nums[j+1] = nums[j+1], nums[j]
}
}
}
}
``` ```
=== "JavaScript" === "JavaScript"
@ -239,7 +251,24 @@ comments: true
=== "Go" === "Go"
```go title="bubble_sort.go" ```go title="bubble_sort.go"
/* 冒泡排序(标志优化)*/
func bubbleSortWithFlag(nums []int) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i := len(nums) - 1; i > 0; i-- {
flag := false // 初始化标志位
// 内循环:冒泡操作
for j := 0; j < i; j++ {
if nums[j] > nums[j+1] {
// 交换 nums[j] 与 nums[j + 1]
nums[j], nums[j+1] = nums[j+1], nums[j]
flag = true // 记录交换元素
}
}
if flag == false { // 此轮冒泡未交换任何元素,直接跳出
break
}
}
}
``` ```
=== "JavaScript" === "JavaScript"