Created
November 14, 2019 17:44
-
-
Save mlavergn/64207207b61effad5053d5cfb355a3c9 to your computer and use it in GitHub Desktop.
Swift Sleep Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// O(n) sort | |
// Technically O(n) since time measures complexity and not a fixed interval | |
// NOTE: This is just for fun, please don't use this in real applications! | |
func sleepSort(_ vals: [Int]) -> [Int] { | |
var result: [Int] = [] | |
let sortDispatch = DispatchQueue(label: "sleepSort", qos: .userInitiated, attributes: .concurrent) | |
let sortGroup = DispatchGroup() | |
_ = vals.map { val in | |
sortDispatch.async(group: sortGroup) { | |
sleep(UInt32(val)) | |
result.append(val) | |
} | |
} | |
sortGroup.wait() | |
return result | |
} | |
print(sleepSort([4,1,3,2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment