Merge pull request #71 from luckydog612/patch-2

Update Sort.go
This commit is contained in:
wangzheng0822 2018-10-22 10:53:00 +08:00 committed by GitHub
commit dba696767c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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]
}
}