Skip to content

Instantly share code, notes, and snippets.

@NoahPeeters
Created November 26, 2017 15:10
Show Gist options
  • Save NoahPeeters/4ec8352b47300e5a5a3b775b7cf20ccf to your computer and use it in GitHub Desktop.
Save NoahPeeters/4ec8352b47300e5a5a3b775b7cf20ccf to your computer and use it in GitHub Desktop.
The awesome quantum logo sort
import Foundation
extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}
func bogoSort<Element: Comparable>(_ array: [Element]) {
let shuffledArray = array.shuffled()
for index in 0..<shuffledArray.count - 1 {
if shuffledArray[index] > shuffledArray[index + 1] {
return
}
}
print(shuffledArray)
}
func quantumBogoSort<Element: Comparable>(_ array: [Element]) {
let threadCount = 200
for _ in 0..<threadCount {
let t = Thread {
bogoSort(array)
}
t.start()
}
}
let arrayToSort = [3, 2, 1, 6, 4]
quantumBogoSort(arrayToSort)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment