Bubble sorting an array in Swift, compiler error on swap

前端 未结 6 1235
闹比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:42

    Swift 5: Generic bubble sort method,

    func bubbleSort(with array: inout [T]) -> [T] {
        for i in 1.. array[j+1] {
                array.swapAt(j, j+1)
            }
        }
        return array
    }
    

    Input:-

    var intArray = [8, 3, 5, 10, 4, -1, 17, 3, 18, 10]
    var floatArray = [12.231, 12.23, 14.5, 3.4, 67.899, 0.0, -1.234]
    var doubleArray = [123.43555, 123.1223332, -121.2212, 23.343434, 1.232434]
    var stringArray = ["Ratheesh", "Srini", "Thangu", "Muthu", "Gopi"]
    
    print(bubbleSort(with: &intArray))
    print(bubbleSort(with: &floatArray))
    print(bubbleSort(with: &doubleArray))
    print(bubbleSort(with: &stringArray))
    

    Output:-

    [-1, 3, 3, 4, 5, 8, 10, 10, 17, 18]
    [-1.234, 0.0, 3.4, 12.23, 12.231, 14.5, 67.899]
    [-121.2212, 1.232434, 23.343434, 123.1223332, 123.43555]
    ["Gopi", "Muthu", "Ratheesh", "Srini", "Thangu"]
    

提交回复
热议问题