Learning Go

I find that a good way to figure out if I like a new language is to write a few classic algorithms in it.

Merge Sort

    package main
    
    func mergeSorted(list1 []int, list2 []int) []int {
    
        m := make([]int,len(list1)+len(list2))
        i,j,k := 0,0,0
    
        for ; i < len(list1) && j < len(list2); k++ {
            if list1[i] < list2[j] {
                m[k] = list1[i]
                i++
            } else {
                m[k] = list2[j]
                j++
            }
        }
        for ; i < len(list1); i++ {
            m[k] = list1[i]
            k++
        }
        for ; j < len(list2); j++ {
            m[k] = list2[j]
            k++
        }
        return m
    }
    
    func msort(lst []int) []int {
        if len(lst) <= 1 {
            return lst
        }
        return mergeSorted( msort(lst[:len(lst)/2]), msort(lst[len(lst)/2:]) )
    }

Insertion Sort

    package main
    
    func isort(arr []int) []int {
        var hole,item int;
        for i := 1; i < len(arr); i++ {
            hole = i
            item = arr[i]
            for hole > 0 && arr[hole-1] > item {
                arr[hole] = arr[hole-1]
                hole--
            }
            arr[hole] = item
        }
        return arr
    }

Quick Sort

    package main
    
    import (
        "math/rand"
    )
    
    func partition(arr []int) int {
    
        ppos := choose_pivot_pos(arr)
        pivot := arr[ppos]
    
        var i,j int = 0,len(arr)-1
        for i <= j {
            if arr[i] < pivot {
                i++
            } else if arr[j] > pivot {
                j--
            } else {
                arr[i],arr[j] = arr[j],arr[i]
                i++
                j--
            }
        }
        return i
    }
    
    func choose_pivot_pos(arr []int) int {
        return int(rand.Int31() % int32(len(arr)))
    }
    
    func qsort(arr []int) []int {
        if len(arr) <= 1 {
            return arr
        }
        ppos := partition(arr)
        qsort(arr[:ppos])
        qsort(arr[ppos+1:])
        return arr
    }

And the unit test framework

This might not be the most idiomatic Go but I really like the spartan syntax, I like the array slices and I really like the ability to swap variable values in one line. I am impressed.