User:Soniakeys/Go/Parallel Naïvesort

Heading text
Program description

Complete program source
package main

import (   "fmt"    "rand" )

func main { s := []string{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"} fmt.Println(s) s = naïveSortP(s) fmt.Println(s) }

func naïveSortP(s []string) []string { if len(s) < 2 { return s   } z := len(s) - 1 r := make(chan []string) for i := range s { rg := rand.New(rand.NewSource(0)) sc := make([]string, len(s)) copy(sc, s)       sc[z], sc[i] = sc[i], sc[z] fmt.Println("trying", sc) go naïveSort(sc[:z], r, rg) }   return <-r }

func naïveSort(s []string, r chan []string, rg *rand.Rand) bool { if len(s) < 2 { s = s[:cap(s)] rv := sorted(s) if rv { fmt.Println("sorted!") r <- s       } return rv   } p := rg.Perm(len(s)) z := len(s) - 1 for _, j := range p { s[z], s[j] = s[j], s[z] if naïveSort(s[:z], r, rg) { return true }       s[z], s[j] = s[j], s[z] }   return false }

func sorted(s []string) bool { for i := 1; i < len(s); i++ { if s[i] < s[i-1] { return false }   }    return true }

Long lines
s := []string{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"}

Make
sc := make([]string, len(s))

Channels
r := make(chan []string)

User defined New functions
rg := rand.New(rand.NewSource(0))

For/range with omitted variable
for i := range s {

Copy built-in function
copy(sc, s)

Go statement
go naïveSort(sc[:z], r, rg)

Method call
p := rg.Perm(len(s))

Channel send
r <- s

Channel receive
return <-r