DEV Community

Naveen
Naveen

Posted on

Insertion sort using go

image

Photo by Jarosław Kwoczała on Unsplash

Sorting is always a good start point to learn algorithm. Not only it is easy but it also quite challenging too, that's why we have plenty of sorting algorithms are available.

Now, lets talk about Insertion Sort.

Insertion Sort

Insertion Sort algorithm is relatively a simple an efficient algorithm for sorting a smaller array.
It works the way many people sort a hand of playing cards.

We start an empty hand, remove one card from the table and one card into the hand in the correct position.
For that, we need to compare the previous card from hand. If the previous value is bigger than new card then move previous card to right and move current card to the left (Basically, just swap position based on value).
image
Enough talk, let do this in code.

package main

import "fmt"

func main() {
    // declare an array
    items := [6]int{5, 2, 4, 6, 1, 3}
    // calculate length of array
    var n = len(items)
    // loop through array
    for i := 1; i < n; i++ {
        // set limit for current index (for leftside shift)
        j := i
        // loop through array until we reach the last element
        for j > 0 {
            // If the Item from right side is greater than left side
            // we need to swap the values
            if items[j-1] > items[j] {
                items[j-1], items[j] = items[j], items[j-1]
            }
            /*
            * else {
            * no need to swap, because this unit already sortted
            * }*/

            // reduce inner index by one
            j = j - 1
        }
    }
    fmt.Println(items)
}

Enter fullscreen mode Exit fullscreen mode

Gist Link :https://gist.github.com/NaveenDA/3f71583594a2795c838ab4e044c09d35

I recommend everyone should try this algorithm in your favorite programming language. It improve our knowledge and more importantly it gives some challenges until we solve it.


Thanks for reading <3.

Top comments (0)