Friday, July 1, 2011

Sorting is Linear - also in Go!

Wrttien in Go

package main

/*
   Sorting a list of positive int64 values is linear, also in Go!
   Author: Harald Schilly 
   Based on some bash script I found somewhere on the internetz ...
*/

import "time"

func main() {
  var vals = []int64 { 55, 1, 9, 0, 31, 11, 90, 11 }

  var ret  = make(chan int64)
  var done = make(chan bool)

  // main loop, just a single for loop
  for _, v := range vals {
    go func(v int64) {
      // if it doesn't sort well, increase the 1e5
      time.Sleep(1e5 * v)
      ret <- v
    } (v)
  }

  // output iterates over all results in the ret channel
  go func() {
    for i := 0; i < len(vals); i++ {
      println(<-ret)
    }
    done <- true
  }()

  <-done
}

No comments:

Post a Comment