forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
37 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
|
||
} | ||
} |