Robert A Decker Programming Repository


Notes and articles that will reduce the pain

iOS Swift Array Bogosort

Robert Decker - Saturday, November 04, 2017

Sadly iOS's Swift Array class doesn't have a bogosort function. Here is my implementation.
extension Array {
    // first, add a function to Array that returns a boolean for whether the array is sorted or not, > or <
    func isSorted(_ isOrderedBefore: (Element, Element) -> Bool) -> Bool {
        for i in 1..<self.count {
            if !isOrderedBefore(self[i-1], self[i]) {
                return false
            }
        }
        return true
    }

    // we also need a function that randomizes the array
    mutating func randomize() {
        self.sort(by: {_, _ in arc4random() % 2 == 0})
    }

    // and finally we add the bogosort function
    func bogoSort() {
        while(!arr.isSorted(<)) {
            arr.randomize()
        }
    }
}
Output:
var arr: [Int] = [0, 4, 2, 3, 5]
[0, 4, 2, 3, 5]

arr.bogoSort()
[0, 2, 3, 4, 5]

It only had to randomize the array 456 times.