feat: Add Insertion sort
This commit is contained in:
+7
-1
@@ -1,7 +1,13 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"dsa.go/pkg/algo"
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println("Learning and Practicing DSA in Go.")
|
fmt.Println("Learning and Practicing DSA in Go.")
|
||||||
|
|
||||||
|
algo.InsertionSort([]int{5, 2, 4, 6, 1, 3}, 6)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package algo
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func InsertionSort(a []int, n int) {
|
||||||
|
fmt.Println("-- Insertion Sort --")
|
||||||
|
fmt.Printf("Input: %v\n", a)
|
||||||
|
|
||||||
|
for i := 1; i < n; i++ {
|
||||||
|
key := a[i]
|
||||||
|
j := i - 1
|
||||||
|
for ; j >= 0 && a[j] > key; j-- {
|
||||||
|
a[j+1] = a[j]
|
||||||
|
}
|
||||||
|
a[j+1] = key
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Output: %v\n", a)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user