import Foundation
func contains(array: [Int], rand: Int) -> Bool{
for number in array {
if(number == rand){
return true
}
}
return false
}
func quicksort(array: [Int], lowIndex: Int, highIndex: Int){
if(lowIndex >= highIndex){
return;
}
let pivot: Int = array[highIndex]
var leftPointer = lowIndex
var rightPointer = highIndex
while(leftPointer < rightPointer){
while(array[leftPointer] <= pivot && leftPointer < rightPointer){
leftPointer = leftPointer 1
}
while(array[rightPointer] >= pivot && leftPointer < rightPointer){
rightPointer = rightPointer - 1
}
array.swapAt(leftPointer, rightPointer)
}
if(array[leftPointer] > array[highIndex]){
array.swapAt(leftPointer, highIndex)
} else{
leftPointer = highIndex
}
quicksort(array: array, lowIndex: lowIndex, highIndex: leftPointer - 1)
quicksort(array: array, lowIndex: leftPointer 1, highIndex: highIndex)
}
func quicksort(array: [Int]){
quicksort(array: array, lowIndex: 0, highIndex: array.count - 1)
}
func main(){
var array = [Int.random(in: 0..<30)]
var jArray = 0
while(jArray < 20){
let rand = Int.random(in: 0..<21)
if(!contains(array: array, rand: rand)){
array.append(rand)
jArray = jArray 1
}
else{}
}
print("Before:")
print(array)
print("\nAfter:")
quicksort(array: array)
print(array)
}
main()
I tried to implement the Quicksort like that in swift and the swapAt method throws an error which says: error: cannot use mutating member on immutable value: 'array' is a 'let' constant. I tried several fixes but somehow nothing seemed to work so I hope that someone here can help me with that, thank you.
CodePudding user response:
The parameters to a function are effectively let
constants. There are two ways you can resolve the problem which represent different programming paradigms. The first is to make the parameters inout
and the second is to return the sorted array.
Using inout
func quicksort(array: inout [Int], lowIndex: Int, highIndex: Int)
{
// sort the array
}
Returning the sorted array
func quicksort(array: [Int]) -> [Int]
{
var sortingArray = array
// Do the pivot stuff
return quicksort(lower bit of sortingArray) quicksort(upper bit of sortingArray)
}
You can do some jazzy stuff with generics and array slices in the latter case to make it look nice and eliminate the need to pass indexes.