Bubble sorting an array in Swift, compiler error on swap

前端 未结 6 1276
闹比i
闹比i 2021-01-20 05:22

I wrote a really simple bubble sort for a card game. It takes an array of \"Card\" objects, each of which has a an \"order\" attribute which indicates the value to be sorted

6条回答
  •  無奈伤痛
    2021-01-20 05:35

    I played with the following using swift 3. Hope it'll help some people who come here.

    bubble sort:

    func bubble(arr: inout [Int]) {
        for i in (1.. arr[j + 1] {
                swap(&arr[j], &arr[j + 1])
            }
        }
    }
    

    using stride:

    func bubbleStride(arr: inout [Int]) {
        for i in stride(from: arr.count - 1, to: 1, by: -1) {
            for j in 0.. arr[j + 1] {
                swap(&arr[j], &arr[j + 1])
            }
        }
    }
    

    using while:

    func bubbleWhile(arr: inout [Int]) {
        var i = arr.count - 1
        while(i > 0) {
            var j = 0
            while(j < i) {
                if arr[j] > arr[j + 1] {
                    swap(&arr[j], &arr[j + 1])
                }
                j += 1
            }
            i -= 1
        }
    }
    

    This can be used to generate a random array of integers:

    import Cocoa
    
    func ints(cnt: Int, ceiling: Int) -> [Int] {
        let arr = Array(repeating: 0, count: cnt)
        return arr.map { _ in Int(arc4random_uniform(UInt32(ceiling))) }
    }
    

    E.g.:

    let a = ints(cnt: 10, ceiling: 100)
    print(a)
    
    var b = a
    bubble(arr: &b)
    print(b)
    

    output:

    [13, 30, 68, 19, 1, 4, 28, 65, 96, 13]
    [1, 4, 13, 13, 19, 28, 30, 65, 68, 96]
    

提交回复
热议问题