/* * Timing of sorting in Go. * Idea, build a struct of a string and a random number * Then sort by either he string or the number * *@author ggtowell * created: July 3, 2021 */ package main import ( "bytes" "fmt" "math/rand" "sort" "time" ) // a struct containing a random string and random number type NumAndString struct { num int str string } // a slice containing the struct type NumAndStringSlice []NumAndString // Other than the name, the same as the prior type type StringSlice NumAndStringSlice // a global holding an instance of NumAndStirngSlice var aaa NumAndStringSlice // Associate three functions with the type NumAndStingSlice // These will result in sorting on the number // These three functions are required to implement sorting // In Java parlance, you implement a interface of these three functions func (p NumAndStringSlice) Len() int { return len(p) } func (p NumAndStringSlice) Swap(i, j int) { p[i],p[j] = p[j],p[i] } func (p NumAndStringSlice) Less(i, j int) bool { return p[i].num < p[j].num } // Associate three functions with the type StingSlice // These will result in sorting on the stirng func (p StringSlice) Len() int { return len(p) } func (p StringSlice) Swap(i, j int) { p[i],p[j] = p[j],p[i] } func (p StringSlice) Less(i, j int) bool { return p[i].str < p[j].str } /* * Build a random string of the given length (lower case only) */ func randString(len int, r1 *rand.Rand) string { if len==0 { return "" } var buf bytes.Buffer for i := 0; i < len; i++ { buf.WriteString(string('a' + r1.Intn(26))) } return buf.String() } func main() { //Initialize the random number generatort s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) now := time.Now(); doSort(10000000, r1, true) thn := time.Now(); diff := thn.Sub(now) fmt.Println(diff); } /* * Build the thing to be sorted, then sort it * @param num -- the size of the thing to be sorted * @param r1 -- an initialized instance of a random number generator * @param stringSortP -- if true, sort on the stirng, else sort on the number */ func doSort(num int, r1 *rand.Rand, stringSortP bool) { // initialized the slice aaa = make(NumAndStringSlice, num) // set the length of the string to be sorted strLen:=0 if stringSortP { strLen = 6 } // fill the slice for i := 0; i < num; i++ { aaa[i] = NumAndString{r1.Intn(num), randString(strLen,r1)} } // do the sort if !stringSortP { sort.Sort(aaa) } else { sort.Sort(StringSlice(aaa)) } // show the first couple of items to verify that the sort worked for i:=0; i < 5; i++ { fmt.Printf("%v\n", aaa[i]) } }