go

Max-heap in Go

tung's picture

I was helping somebody on a forum a few days ago with a C++ max-heap implementation. I thought it might be fun to try it out in Go.

package main
 
import (
    "container/vector";
    "flag";
    "rand";
    "time";
)
 
var num = flag.Int("n", 10, "number of elements to heap sort")
 
func main() {
    flag.Parse();
    rand.Seed(time.Nanoseconds());
    v := vector.NewIntVector(*num);
    for i := 1; i <= *num; i++ {
        v.Set(i - 1, rand.Int() % 100)
    }
    heapSort(v);
    printHeap(v, 0, 0);
}
 
func left(i int) int {
    return i * 2 + 1
}
 
func right(i int) int {
    return i * 2 + 2
}
 
func parent(i int) int {
    return (i - 1) / 2
}
 
// Swap vec[i] with its parent if its larger. Stop at the top.
func maxHeapify(vec *vector.IntVector, i int) {
    if i <= 0 {
        return
    }
    p := parent(i);
    if vec.At(p) < vec.At(i) {
        temp := vec.At(p);
        vec.Set(p, vec.At(i));
        vec.Set(i, temp);
        maxHeapify(vec, p);
    }
}
 
// Given a list of numbers in any order, max heap sort it.
func heapSort(vec *vector.IntVector) {
    for i := 0; i < vec.Len(); i++ {
        maxHeapify(vec, i)
    }
}
 
func printHeap(vec *vector.IntVector, i int, nest int) {
    if i >= vec.Len() {
        return
    }
    for n := 0; n < nest; n++ {
        print("    ")
    }
    print(vec.At(i));
    print("\n");
    printHeap(vec, left(i), nest + 1);
    printHeap(vec, right(i), nest + 1);
}
Read more »

goblog: A proof-of-concept blog in Go

tung's picture

As if I wasn't bored enough, I've written a proof-of-concept blog using Go, that new language out of Google. I blogged about this language before, but I wanted to give it a real test drive, so I came up with this.

goblog on github

Pointers ahoy

The first thing I noticed when I got started was pointer trouble on my part. Go still has pointers like in C, but some of the syntax smooths over the differences.

Read more »

Impressions of Go: From the guy who learned it in 2 days

tung's picture

Go is that new-fangled language out of Google, and though I won't describe it (been done much better by somebody else), I will give a few opinions from the point of view of somebody who's written some code in it.

C-like syntax

It looks like C. Braces, parens and semi-colons all make yet another cameo in a programming language.

Read more »
Syndicate content