package main
import (
"fmt"
"strconv"
)
func insertionSort(arr []int) {
// Un-sorted array from position 1 to length -1
for i := 1; i < len(arr); i++ {
// Take the left most item in an un-sorted array to temp variable
var temp = arr[i]
// Mark the left most position as empty or hole
var holePosition = i
// Traverse the sorted array from right to left direction
// Move the item from the sorted array to the empty position (i.e. holePosition) only if the temp variable is less then
// Mark the current item's position as empty by decrementing the value by one
for holePosition > 0 && arr[holePosition - 1] > temp {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
// Once the comparison done, move the value in temp variable to the lastly marked empty position
arr[holePosition] = temp
}
}
func printArray(arr []int) {
// Loop the item and print each item in the console with white space seperated
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
fmt.Print("After Sorting: ")
printArray(arr)
}
出力
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15