Use a slice
This commit is contained in:
parent
3f218586ca
commit
1da93e8406
37
main.go
37
main.go
|
@ -1,6 +1,9 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// This is the map we want to sort
|
||||
|
@ -17,23 +20,25 @@ func main() {
|
|||
m[9] = 99
|
||||
|
||||
iterations := 0
|
||||
var slice []int
|
||||
var sorted = false
|
||||
for !sorted {
|
||||
sorted = true
|
||||
var previous int
|
||||
var passed = false
|
||||
|
||||
// We put the map in a slice to have something more deterministic to work with
|
||||
slice = nil
|
||||
for _, msg := range m {
|
||||
if !passed {
|
||||
previous = msg
|
||||
passed = true
|
||||
continue
|
||||
}
|
||||
if msg < previous {
|
||||
sorted = false
|
||||
break
|
||||
}
|
||||
previous = msg
|
||||
slice = append(slice, msg)
|
||||
}
|
||||
|
||||
// Check if the slice is sorted
|
||||
sted := sort.SliceIsSorted(slice, func(i, j int) bool {
|
||||
return slice[i] < slice[j]
|
||||
})
|
||||
if sted {
|
||||
sorted = true
|
||||
break
|
||||
}
|
||||
|
||||
iterations++
|
||||
fmt.Printf("\rIteration %d, no miracle happened yet.", iterations)
|
||||
}
|
||||
|
@ -41,10 +46,8 @@ func main() {
|
|||
fmt.Println("Sorted.")
|
||||
fmt.Println("Iterations: ", iterations)
|
||||
|
||||
// for i := 0; i < 5; i++ {
|
||||
fmt.Println("MAP:")
|
||||
for index, msg := range m {
|
||||
for index, msg := range slice {
|
||||
fmt.Println(index, ": ", msg)
|
||||
}
|
||||
//}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue