DEV Community

Cover image for Sorting Algorithms in Go
Adnan Babakan (he/him)
Adnan Babakan (he/him)

Posted on • Updated on

Sorting Algorithms in Go

Hey, Dev.to community!

As a little project, I've written some famous sort algorithms using Go. I hope this would be useful for you!

Table of contents

Bubble Sort

Bubble sort is a very easy algorithm to follow. You need to check every element of an array against the next element to see if it is larger, if so, you need to swap them. You should do this task as many times as finally there wouldn't be any swap action needed.



package main

import "fmt"

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11}

    var isDone = false

    for !isDone {
        isDone = true
        var i = 0
        for i < len(n) - 1 {
            if n[i] > n[i + 1] {
                n[i], n[i + 1] = n[i + 1], n[i]
                isDone = false
            }
            i++
        }
    }

    fmt.Println(n)
}


Enter fullscreen mode Exit fullscreen mode

Recursive Bubble Sort

Recursive bubble sort is a variation of the normal bubble sort (also knows as iterative bubble sort). This works the same as the iterative bubble sort with no extra advantages over time or complexity XD. But this will improve your understanding of bubble sort and recursion:



package main

import "fmt"

func bubbleSort(arr []int, size int) []int {
    if size == 1 {
        return arr
    }

    var i = 0
    for i < size-1 {
        if arr[i] > arr[i+1] {
            arr[i], arr[i+1] = arr[i+1], arr[i]
        }

        i++
    }

    bubbleSort(arr, size - 1)

    return arr
}

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11}

    fmt.Println(bubbleSort(n, len(n)))
}



Enter fullscreen mode Exit fullscreen mode

Insertion Sort

Insertion sort is a famous sorting algorithm that works like sorting a deck of cards in hand. As you proceed through the elements of an array you would move it back until it is in the correct place.

Insertion Sort

Credits to https://www.geeksforgeeks.org/


package main

import "fmt"

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11}

    var i = 1
    for i < len(n) {
        var j = i
        for j >= 1 && n[j] < n[j - 1] {
            n[j], n[j - 1] = n[j - 1], n[j]

            j--
        }

        i++
    }

    fmt.Println(n)
}


Enter fullscreen mode Exit fullscreen mode

Selection Sort

Selection sort is quite interesting and yet simple. What you need to do is simply replace the current element in iteration by the lowest value on the right. As you go further the left part of the array is sorted, and you don't need to check for the last element.

Selection sort



package main

import "fmt"

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11}

    var i = 1
    for i < len(n) - 1 {
        var j = i + 1
        var minIndex = i

        if j < len(n) {
            if n[j] < n[minIndex] {
                minIndex = j
            }
            j++
        }

        if minIndex != i {
            var temp = n[i]
            n[i] = n[minIndex]
            n[minIndex] = temp
        }

        i++
    }

    fmt.Println(n)
}


Enter fullscreen mode Exit fullscreen mode

Merge Sort

Merge is a quite fast sorting algorithm. In a merge sort, you should utilize the divide-and-conquer practice. First, you'll divide the passed array by 2 recursively, until you reach the length of 1, then you should merge them. To merge two arrays that we know are already sorted themselves you can implement a simple function called merge.

Merge sort



package main

import "fmt"

func merge(fp []int, sp []int) []int {
    var n = make([]int, len(fp)+len(sp))

    var fpIndex = 0
    var spIndex = 0

    var nIndex = 0

    for fpIndex < len(fp) && spIndex < len(sp) {
        if fp[fpIndex] < sp[spIndex] {
            n[nIndex] = fp[fpIndex]
            fpIndex++
        } else if sp[spIndex] < fp[fpIndex] {
            n[nIndex] = sp[spIndex]
            spIndex++
        }

        nIndex++
    }

    for fpIndex < len(fp) {
        n[nIndex] = fp[fpIndex]

        fpIndex++
        nIndex++
    }

    for spIndex < len(sp) {
        n[nIndex] = sp[spIndex]

        spIndex++
        nIndex++
    }

    return n
}

func mergeSort(arr []int) []int {
    if len(arr) == 1 {
        return arr
    }

    var fp = mergeSort(arr[0 : len(arr)/2])
    var sp = mergeSort(arr[len(arr)/2:])

    return merge(fp, sp)

}

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11, 8}

    fmt.Println(mergeSort(n))
}


Enter fullscreen mode Exit fullscreen mode

Counting Sort

Counting sort is a really simple yet complicated sorting algorithm. To understand how counting sort works you can watch the video below from GeekforGeeks:

Here is the Go code:



package main

import "fmt"

func countSort(arr []int) []int {
    var max = arr[0]

    var i = 1
    for i < len(arr) {
        if arr[i] > max {
            max = arr[i]
        }

        i++
    }

    var indices = make([]int, max + 1)

    var j = 0
    for j < len(arr) {
        indices[arr[j]]++

        j++
    }

    var k = 1
    for k < len(indices) {
        indices[k] += indices[k - 1]

        k++
    }

    var result = make([]int, len(arr))

    var m = 0
    for m < len(arr) {
        result[indices[arr[m]] - 1] = arr[m]
        indices[arr[m]]--

        m++
    }

    return result
}

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11}

    fmt.Println(countSort(n))
}



Enter fullscreen mode Exit fullscreen mode

I will complete this list by time.

BTW! Check out my free Node.js Essentials E-book here:

Top comments (5)

Collapse
 
jacobalberty profile image
Jacob Alberty

Your bubble sort contains an error. The output is [1 2 9 7 39 11 54] which is clearly not fully sorted. It only does one iteration. Just need to add an isDone = false inside of the if statement

package main

import "fmt"

func main() {
    var n = []int{1, 39, 2, 9, 7, 54, 11}

    var isDone = false

    for !isDone {
        isDone = true
        var i = 0
        for i < len(n)-1 {
            if n[i] > n[i+1] {
                n[i], n[i+1] = n[i+1], n[i]
                isDone = false
            }
            i++
        }
    }

    fmt.Println(n)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adnanbabakan profile image
Adnan Babakan (he/him)

Thank you so much for spotting the error. Don't know how missed that. :)

Collapse
 
robert profile image
Robert Wallis

Nice article!

Go has swap without temp

n[i], n[i + 1] = n[i + 1], n[i]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adnanbabakan profile image
Adnan Babakan (he/him)

Oh nice, thanks for the tip. I just started to learn Go and it is fascinating. :)

Collapse
 
blitzkriegcoding profile image
Yrvin Escorihuela

What it means those pronouns in your bio?