Quicksort in Swift gives error
I am writing Quick Sort using a higher order function in Swift, but it gives
error: 'Int' is not convertible to '[Int]'
return quickSort(array: lesser) + [pivot] + quickSort(array: greater)
Here is the code:
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)
}
There is an error in the last line.
+3
Rahul
source
to share
2 answers
I can't tell you why this isn't working (I think it should), but I can tell you how to fix it.
Replace this
return quickSort(array: lesser) + [pivot] + quickSort(array: greater)
with this
return
quickSort(array: lesser) as [Int] +
[pivot] +
quickSort(array: greater)
+3
Luca angeletti
source
to share
Indeed, the compiler gets confused with data types in a multi-operator formula, including the return type of the function it is currently compiling.
There are probably many ways to help the compiler. Here's one that isn't associated with a redundant type (the key makes the pivot an array [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)
}
0
Alain T.
source
to share