SortingAlgorithms/insertion.go

33 lines
722 B
Go
Raw Normal View History

2022-03-05 20:20:33 +03:00
package main
import (
"fmt"
)
func main(){
arr := []int{64, 25, 12, 22, 11, 14, 1, 3, 2}
n := len(arr)
fmt.Println("Unsorted:",arr)
for i := 1; i < n; i++{
key := arr[i]
j := i - 1;
for j >= 0 && arr[j] > key{
arr[j + 1] = arr[j]
j = j - 1
}
arr[j + 1] = key
}
fmt.Println("Sorted:",arr)
}
/*
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor,
compare it to the elements before.
Move the greater elements one position up to make space for the swapped element.
*/