DEV Community


Posted on


Insertion sort using go


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).
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

Enter fullscreen mode Exit fullscreen mode

Gist Link :

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)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another “Coder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.