miracle-sort/main.go

61 lines
1.1 KiB
Go
Raw Permalink Normal View History

2019-04-07 09:15:06 +00:00
package main
2019-04-07 12:04:32 +00:00
import (
"fmt"
2019-04-07 12:19:46 +00:00
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/number"
2019-04-07 12:04:32 +00:00
"sort"
2019-04-07 12:10:37 +00:00
"time"
2019-04-07 12:04:32 +00:00
)
2019-04-07 09:15:06 +00:00
func main() {
// This is the map we want to sort
2019-04-07 09:52:20 +00:00
m := make(map[int]int)
m[0] = 00
m[1] = 11
m[2] = 44
m[3] = 33
m[4] = 22
m[5] = 55
m[6] = 66
m[7] = 77
m[8] = 88
m[9] = 99
2019-04-07 09:15:06 +00:00
2019-04-07 12:10:37 +00:00
start := time.Now()
2019-04-07 09:47:41 +00:00
iterations := 0
2019-04-07 12:04:32 +00:00
var slice []int
2019-04-07 09:47:41 +00:00
var sorted = false
2019-04-07 12:04:32 +00:00
2019-04-07 12:19:46 +00:00
p := message.NewPrinter(language.English)
2019-04-07 12:10:37 +00:00
for !sorted {
2019-04-07 12:04:32 +00:00
// We put the map in a slice to have something more deterministic to work with
slice = nil
2019-04-07 09:47:41 +00:00
for _, msg := range m {
2019-04-07 12:04:32 +00:00
slice = append(slice, msg)
}
// Check if the slice is sorted
2019-04-07 12:11:21 +00:00
if sort.SliceIsSorted(slice, func(i, j int) bool {
2019-04-07 12:04:32 +00:00
return slice[i] < slice[j]
2019-04-07 12:11:21 +00:00
}) {
2019-04-07 12:04:32 +00:00
sorted = true
break
2019-04-07 09:47:41 +00:00
}
2019-04-07 12:04:32 +00:00
2019-04-07 09:47:41 +00:00
iterations++
2019-04-07 12:19:46 +00:00
p.Printf("\rIteration %v, no miracle happened yet.", number.Decimal(iterations))
2019-04-07 09:47:41 +00:00
}
2019-04-07 12:10:37 +00:00
fmt.Println("\nSorted.")
fmt.Printf("Took %v\n", time.Since(start))
fmt.Printf("Iterations: %d\n", iterations)
2019-04-07 09:47:41 +00:00
2019-04-07 12:10:37 +00:00
fmt.Println("Sorted slice:")
2019-04-07 12:04:32 +00:00
for index, msg := range slice {
2019-04-07 09:15:06 +00:00
fmt.Println(index, ": ", msg)
}
}