Skip to content

Instantly share code, notes, and snippets.

@mlavergn
Created November 14, 2019 17:44
Show Gist options
  • Save mlavergn/64207207b61effad5053d5cfb355a3c9 to your computer and use it in GitHub Desktop.
Save mlavergn/64207207b61effad5053d5cfb355a3c9 to your computer and use it in GitHub Desktop.
Swift Sleep Sort
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