Skip to content

Commit

Permalink
Update Sort.go
Browse files Browse the repository at this point in the history
  • Loading branch information
yayiyo authored Oct 16, 2018
1 parent 4e0649e commit 46ded91
Showing 1 changed file with 37 additions and 25 deletions.
62 changes: 37 additions & 25 deletions go/11_sorts/Sort.go
Original file line number Diff line number Diff line change
@@ -1,54 +1,66 @@
package _1_sorts

func BubbleSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
/*
冒泡排序、插入排序、选择排序
*/

//冒泡排序,a是数组,n表示数组大小
func BubbleSort(a []int, n int) {
if n <= 1 {
return
}
for i := arrLen - 1; i > 0; i-- {
for j := 0; j < i; j++ {
for i := 0; i < n; i++ {
// 提前退出标志
flag := false
for j := 0; j < n-i-1; j++ {
if a[j] > a[j+1] {
tmp := a[j+1]
a[j+1] = a[j]
a[j] = tmp
a[j], a[j+1] = a[j+1], a[j]
//此次冒泡有数据交换
flag = true
}
}
// 如果没有交换数据,提前退出
if !flag {
break
}
}
}

func InsertSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
// 插入排序,a表示数组,n表示数组大小
func InsertionSort(a []int, n int) {
if n <= 1 {
return
}
for i := 1; i < arrLen; i++ {
v := a[i]
for i := 1; i < n; i++ {
value := a[i]
j := i - 1
//查找要插入的位置并移动数据
for ; j >= 0; j-- {
if a[j] > v {
if a[j] > value {
a[j+1] = a[j]
} else {
break
}
}
a[j+1] = v
a[j+1] = value
}
}

func SelectionSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
// 选择排序,a表示数组,n表示数组大小
func SelectionSort(a []int, n int) {
if n <= 1 {
return
}
for i := 0; i < arrLen; i++ {
for i := 0; i < n; i++ {
// 查找最小值
minIndex := i
for j := i + 1; j < arrLen; j++ {
for j := i + 1; j < n; j++ {
if a[j] < a[minIndex] {
minIndex = j
}
}
if minIndex != i {
tmp := a[minIndex]
a[minIndex] = a[i]
a[i] = tmp
}
// 交换
a[i], a[minIndex] = a[minIndex],a[i]

}
}

0 comments on commit 46ded91

Please sign in to comment.