Swift中的快速排序给出了错误

时间:2017-04-24 18:20:55

标签: swift swift3

我正在使用Swift中的高阶函数编写一个快速排序,但它正在给出

error: 'Int' is not convertible to '[Int]'
return quickSort(array: lesser) + [pivot] + quickSort(array: greater)

以下是代码:

func quickSort(array: [Int]) -> [Int] {
    var array = array

    if array.isEmpty {return []}

    let pivot = array.remove(at: 0)
    let lesser = array.filter { $0 < pivot }
    let greater = array.filter { $0 >= pivot }

    return quickSort(array: lesser) + [pivot] + quickSort(array: greater)

}

错误在最后一行。

3 个答案:

答案 0 :(得分:3)

我不能告诉你为什么它不起作用(我认为应该),但我可以告诉你如何解决它

替换此

return quickSort(array: lesser) + [pivot] + quickSort(array: greater)

用这个

return
    quickSort(array: lesser) as [Int] +
    [pivot] +
    quickSort(array: greater)

答案 1 :(得分:0)

编译器确实在涉及当前正在编译的函数的返回类型的多操作公式中与数据类型混淆。

可能有很多方法可以帮助编译器。这是一个不涉及冗余类型转换的(关键是使pivot成为[Int]数组):

func quickSort(array: [Int]) -> [Int] 
{
    if array.count < 2 { return array }

    let pivotValue = array.first!  
    let lesser     = array.filter{ $0 < pivotValue }
    let greater    = array.filter{ $0 > pivotValue }
    let pivot      = Array(repeating: pivotValue, 
                               count: array.count - lesser.count - greater.count) 

    return  quickSort(array:lesser) + pivot + quickSort(array:greater)
}

答案 2 :(得分:0)

您也可以尝试

func partition(_ inputArray: [Int], startIndex: Int, endIndex: Int)-> (Int, [Int]) {
    var array = inputArray
    var index = startIndex
    if startIndex < endIndex {
        let pivot = array[endIndex]

        for demo in startIndex..<endIndex {
            if array[demo] <= pivot {
                (array[index], array[demo]) = (array[demo], array[index])
                index += 1
            }
        }
        (array[index], array[endIndex]) = (array[endIndex], array[index])

    }
   return (index, array)
}


func QuickSort(_ input: [Int], startIndex: Int, endIndex: Int)-> [Int] {
    var array = input
    if startIndex < endIndex {
         let pivot = partition(array, startIndex: startIndex, endIndex: endIndex)
       let index = pivot.0
        array = pivot.1
       array = QuickSort(array, startIndex: startIndex, endIndex: index-1)
        array = QuickSort(array, startIndex: index+1, endIndex: endIndex)
    }
    return array
}