feat: 添加排序包
This commit is contained in:
parent
64844c34c7
commit
caae2794c0
3
go_solutions/go.mod
Normal file
3
go_solutions/go.mod
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
module git.icoding.fun/yigencong/algorithm/go_solutions
|
||||||
|
|
||||||
|
go 1.23.2
|
14
go_solutions/main.go
Normal file
14
go_solutions/main.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"git.icoding.fun/yigencong/algorithm/go_solutions/sort"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
arr := []int{64, 34, 25, 12, 22, 11, 90}
|
||||||
|
fmt.Println("原始数组:", arr)
|
||||||
|
sort.BubbleSort(arr)
|
||||||
|
fmt.Println("排序后数组:", arr)
|
||||||
|
}
|
17
go_solutions/sort/bubble-sort.go
Normal file
17
go_solutions/sort/bubble-sort.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package sort
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.icoding.fun/yigencong/algorithm/go_solutions/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BubbleSort 冒泡排序算法
|
||||||
|
func BubbleSort(arr []int) {
|
||||||
|
n := len(arr)
|
||||||
|
for i := 0; i < n-1; i++ {
|
||||||
|
for j := 0; j < n-i-1; j++ {
|
||||||
|
if arr[j] > arr[j+1] {
|
||||||
|
utils.Swap(&arr[j], &arr[j+1]) // 使用 Swap 函数交换元素
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
6
go_solutions/utils/sort-utils.go
Normal file
6
go_solutions/utils/sort-utils.go
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
// 交换数组两个位置的元素
|
||||||
|
func Swap(a, b *int) {
|
||||||
|
*a, *b = *b, *a
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user