Skip to content

Instantly share code, notes, and snippets.

@foo0x29a
Last active March 17, 2019 05:26
Show Gist options
  • Save foo0x29a/9ee42498346724e92d9a05414d598f5a to your computer and use it in GitHub Desktop.
Save foo0x29a/9ee42498346724e92d9a05414d598f5a to your computer and use it in GitHub Desktop.
Sorting in Golang
package main
import (
"fmt"
)
func bubbleSort(s[]int) []int {
A := make([]int, len(s))
copy(A, s)
for i := 0; i < len(A); i++ {
for j := 0; j < len(A)-1; j++ {
if A[j] > A[j+1] {
tmp := A[j]
A[j] = A[j+1]
A[j+1] = tmp
}
}
}
return A
}
func insertionSort(s[]int) []int {
A := make([]int, len(s))
copy(A,s)
for i := 1; i < len(A); i++ {
j := i
v := A[i]
for ; j > 0 && v < A[j-1]; j-- {
A[j] = A[j-1]
}
A[j] = v
}
return A
}
func selectionSort(s[]int) []int {
A := make([]int, len(s))
copy(A,s)
for i := 0; i < len(A); i++ {
min := i
for j := i+1; j < len(A); j++ {
if A[j] < A[min]{
min = j
}
}
tmp := A[min]
A[min] = A[i]
A[i] = tmp
}
return A
}
func main() {
unsorted := []int{7,4,5,2,6,9,1}
sorted := bubbleSort(unsorted)
fmt.Printf("unsorted: %v\n", unsorted)
fmt.Printf("sorted: %v\n", sorted)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment