# 使用golang学习算法（1）-排序

freewebsys · · 1518 次点击 · · 开始浏览

## 1，插入排序

```package main

func InsertSort(a []int) {
for j := 1; j < len(a); j++ {
var key = a[j]
var i = j - 1
for ; i >= 0 && a[i] > key; i-- { //a[i] > key 是按照升序排列，a[i] < key 是按照降序排列。
a[i+1] = a[i]
}
a[i+1] = key
for _, v := range a {
print(v, ",")
}
println()
}
}

func main() {
a := []int{5, 2, 4, 6, 1, 3}
for _, v := range a {
print(v, ",")
}
println()
InsertSort(a)
}
```

```	5,2,4,6,1,3,
2,5,4,6,1,3,
2,4,5,6,1,3,
2,4,5,6,1,3,
1,2,4,5,6,3,
1,2,3,4,5,6,```

## 2，冒泡排序

```package main

func BubbleSort(a []int) {
for i := 0; i <= len(a)-2; i++ {
for j := len(a) - 1; j >= i+1; j-- {
if a[j] < a[j-1] {
a[j], a[j-1] = a[j-1], a[j] //数据交换
}
}
}
}

func main() {
a := []int{5, 2, 4, 6, 1, 3}
for _, v := range a {
print(v, ",")
}
println()
BubbleSort(a)
for _, v := range a {
print(v, ",")
}
println()
}
```

```
5,2,4,6,1,3,
1,2,3,4,5,6,
```

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

## 1，插入排序

```package main

func InsertSort(a []int) {
for j := 1; j < len(a); j++ {
var key = a[j]
var i = j - 1
for ; i >= 0 && a[i] > key; i-- { //a[i] > key 是按照升序排列，a[i] < key 是按照降序排列。
a[i+1] = a[i]
}
a[i+1] = key
for _, v := range a {
print(v, ",")
}
println()
}
}

func main() {
a := []int{5, 2, 4, 6, 1, 3}
for _, v := range a {
print(v, ",")
}
println()
InsertSort(a)
}
```

```	5,2,4,6,1,3,
2,5,4,6,1,3,
2,4,5,6,1,3,
2,4,5,6,1,3,
1,2,4,5,6,3,
1,2,3,4,5,6,```

## 2，冒泡排序

```package main

func BubbleSort(a []int) {
for i := 0; i <= len(a)-2; i++ {
for j := len(a) - 1; j >= i+1; j-- {
if a[j] < a[j-1] {
a[j], a[j-1] = a[j-1], a[j] //数据交换
}
}
}
}

func main() {
a := []int{5, 2, 4, 6, 1, 3}
for _, v := range a {
print(v, ",")
}
println()
BubbleSort(a)
for _, v := range a {
print(v, ",")
}
println()
}
```

```
5,2,4,6,1,3,
1,2,3,4,5,6,
```