Skip to content

Instantly share code, notes, and snippets.

@xguox
Last active February 19, 2019 03:33
Show Gist options
  • Save xguox/3e7cddafe6c342747c358e9065025b77 to your computer and use it in GitHub Desktop.
Save xguox/3e7cddafe6c342747c358e9065025b77 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func insertionSort(a []int) {
if len(a) <= 1 {
return
}
for i := 1; i < len(a); i++ {
iVal := a[i]
j := i - 1
for ; j >= 0; j-- {
if iVal > a[j] {
break
} else {
a[j+1] = a[j]
}
}
a[j+1] = iVal
}
}
func bubbleSort(a []int) {
l := len(a)
if l <= 1 {
return
}
for i := 0; i < l; i++ {
flag := false
for j := 0; j < len(a)-i-1; j++ {
if a[j+1] < a[j] {
tmp := a[j+1]
a[j+1] = a[j]
a[j] = tmp
flag = true
}
}
if !flag {
break
}
}
}
func selectionSort(a []int) {
l := len(a)
if l <= 1 {
return
}
for i := 0; i < l; i++ {
min := i
for j := i + 1; j < l; j++ {
if a[min] > a[j] {
min = j
}
}
a[i], a[min] = a[min], a[i]
}
}
func main() {
arr := []int{9, 7, 4, 1, 8, 2, 6}
bubbleSort(arr)
// insertionSort(arr)
// selectionSort(arr)
fmt.Println(arr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment