Vacant
睡眠排序SleepSort,又是一个奇葩算法

access_time
brush 195个字
whatshot 646 ℃

原理:根据元素的大小决定协程的睡眠时间,协程睡醒之后就把这个元素传回去,这样传回去的顺序就是由小到大有序的数据了

// SleepSort 睡眠排序 复杂度:????(效率和上面那个猴子排序有的一拼)
// 原理:先睡醒的线程他所表示的元素就是比较小的那个,直接传回去
// 不能有负数,如果有负数可以通过加偏移量来处理!!
// 如果sleep设置过小可能会有误差导致排序失败
func SleepSort(s []int) {
    // 协程传回元素(越小的元素sleep越短,位置就越靠前)
    outChan := make(chan int, len(s))
    // 睡眠协程,传入元素和chan
    sleepRoutine := func(out chan int, x int) {
        // 等待时间: 元素大小 * 500ms
        time.Sleep(time.Millisecond * 500 * time.Duration(x))
        out <- x
    }
    // 启动协程,进行排序
    for i := 0; i < len(s); i++ {
        go sleepRoutine(outChan, s[i])
    }
    // 从chan读出排序好的数据
    for i := 0; i < len(s); i++ {
        s[i] = <-outChan
    }
}

#如无特别声明,该文章均为 Vacant 原创,转载请遵循 署名-非商业性使用 4.0 国际(CC BY-NC 4.0) 协议,即转载请注明文章来源。
#最后编辑时间为: 2022 年 05 月 21 日


create 添加新评论


account_circle
email
language
textsms





关于 DreamCat

主题名称:DreamCat | 版本:X2.6.220211

主题开发:HanFengA7 | TeddyNight | Dev-Leo | CornWorld | WhiteBearcn | DFFZMXJ

Designed by HanFengA7 Power by Typecho

Copyright © 2015-2022 by LychApe All rights reserved!

加我的QQ
加我的微博
加我的支付宝
加我的微信