The Go Programming Language

Source file doc/progs/sortmain.go

     1	// Copyright 2009 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	package main
     6	
     7	import (
     8		"fmt"
     9		"./sort"
    10	)
    11	
    12	func ints() {
    13		data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
    14		a := sort.IntSlice(data)
    15		sort.Sort(a)
    16		if !sort.IsSorted(a) {
    17			panic("fail")
    18		}
    19	}
    20	
    21	func strings() {
    22		data := []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
    23		a := sort.StringSlice(data)
    24		sort.Sort(a)
    25		if !sort.IsSorted(a) {
    26			panic("fail")
    27		}
    28	}
    29	
    30	type day struct {
    31		num       int
    32		shortName string
    33		longName  string
    34	}
    35	
    36	type dayArray struct {
    37		data []*day
    38	}
    39	
    40	func (p *dayArray) Len() int           { return len(p.data) }
    41	func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num }
    42	func (p *dayArray) Swap(i, j int)      { p.data[i], p.data[j] = p.data[j], p.data[i] }
    43	
    44	func days() {
    45		Sunday := day{0, "SUN", "Sunday"}
    46		Monday := day{1, "MON", "Monday"}
    47		Tuesday := day{2, "TUE", "Tuesday"}
    48		Wednesday := day{3, "WED", "Wednesday"}
    49		Thursday := day{4, "THU", "Thursday"}
    50		Friday := day{5, "FRI", "Friday"}
    51		Saturday := day{6, "SAT", "Saturday"}
    52		data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday}
    53		a := dayArray{data}
    54		sort.Sort(&a)
    55		if !sort.IsSorted(&a) {
    56			panic("fail")
    57		}
    58		for _, d := range data {
    59			fmt.Printf("%s ", d.longName)
    60		}
    61		fmt.Printf("\n")
    62	}
    63	
    64	
    65	func main() {
    66		ints()
    67		strings()
    68		days()
    69	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.