4

## 蠻可愛的 golang #43 睡覺排序法

https://ithelp.ithome.com.tw/articles/10154811

https://ithelp.ithome.com.tw/users/20091311/ironman/734

https://ithelp.ithome.com.tw/questions/10199225

``````// sleepSort.go
// Craeted: 2020-07-10 07:28:55
// ---------------------
package main

import (
"fmt"
"math/rand"
"sync"
"time"
)

func main() {
var length int = 10

var originalS []int
var sortedS []int
var wg sync.WaitGroup

rand.Seed(time.Now().Unix())

for i := 0; i < length; i++ {
originalS = append(originalS ,rand.Intn(length * 10))
}

fmt.Println("排序前 :", originalS)
fmt.Printf("開始產生 %d 個 goroutine\n", length)

for _, j := range originalS{
go func(n int) {
defer wg.Done()
time.Sleep(1 * time.Second + time.Duration(n * 10) * time.Millisecond)
fmt.Print(n, " ")
sortedS = append(sortedS, n)
}(j)
}

wg.Wait()
fmt.Println()
fmt.Println("排序後 :", sortedS)
}

``````

### 2 則留言

1

iT邦大神 1 級 ‧ 2020-07-10 09:31:12

XD 真是沒想到有這招(排序一下要睡到最大的秒數XD)

``````import antigravity
``````
0

iT邦大師 1 級 ‧ 2020-07-10 10:08:19

``````// nonSleepSort.go
// Craeted: 2020-07-10 10:04:57
// ---------------------
package main

import (
"fmt"
"math/rand"
"sync"
"time"
)

func main() {
var length int = 10

var originalS []int
var sortedS []int
var wg sync.WaitGroup

rand.Seed(time.Now().Unix())

for i := 0; i < length; i++ {
originalS = append(originalS ,rand.Intn(length * 10))
}

fmt.Println("應海棉寶寶要求,改成不讓你睡排序法!")
fmt.Println("排序前 :", originalS)
fmt.Printf("開始產生 %d 個 goroutine\n", length)

for _, j := range originalS{
go func(n int) {
defer wg.Done()
//time.Sleep(1 * time.Second + time.Duration(n * 10) * time.Millisecond)
fmt.Print(n, " ")
sortedS = append(sortedS, n)
}(j)
}

wg.Wait()
fmt.Println()
fmt.Println("排序後 :", sortedS)
}

``````