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.