User:Soniakeys/Go/Naïvesort

Complete source code
package main

import (   "fmt"    "rand" )

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

func naïveSort(s []string) bool { if len(s) < 2 { return sorted(s[:cap(s)]) }   p := rand.Perm(len(s)) z := len(s) - 1 for _, j := range p { s[z], s[j] = s[j], s[z] if naïveSort(s[:z]) { 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 }

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

Package qualification
fmt.Println(s) naïveSort(s) fmt.Println(s)

UTF-8 identifier
func naïveSort(s []string) bool {

Built-in functions len and cap
if len(s) < 2 { return sorted(s[:cap(s)])

Tuple assignment
s[z], s[j] = s[j], s[z]

For statement
for i := 1; i < len(s); i++ {

Yes, of course there is a better way
package main

import (   "fmt"    "sort" )

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