Sleep sorting-Go implementation

Source: Internet
Author: User

An occasional opportunity to see sleep sorting is an interesting sorting algorithm. It can be said that it is a challenge for us to be familiar with regular sorting. It is a breakthrough in our thinking, a bit like a sharp turn in our brains. The sleep sorting algorithm can only be arranged in ascending order. When the data in the array is printed, sleep is based on its size. In this way, the larger the number, the longer the sleep time. All the numbers enter the sleep status at the same time. If the number is small, it will be printed in advance. Recently, I used the go language and had some understanding of its concurrency. Therefore, using the go language to achieve this sort is a good choice.

// Test project main. gopackage mainimport ("FMT" "time") var flag boolvar container Chan boolvar count int func main () {flag = truecontainer = make (Chan bool, 7) vaR arrays [] Int = [] int {25, 12, 36, 24, 96, 54, 28} var I intfor I = 0; I <Len (arrays ); I ++ {go tosleep (arrays [I])} Go listen (LEN (arrays) for flag {time. sleep (1e9) }}func listen (size INT) {for flag {select {Case <-container: count ++ if Count >=size {flag = falsebreak }}} func tosleep (Data INT) {time. sleep (time. duration (data) FMT. println (data) Container <-true}

I thought I could write it three or two times, but it took nearly half an hour to complete the results. What's hard to say is how to effectively stop the program. A container channel has been used to save some data. When there are so many arrays in the container, all the data has been printed and the program can exit. A small mistake was made during this period. No channel capacity was specified, leading to blocking.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.