Search code examples
swiftquicksort

Apply void function on array


I am learning swift right now and wanted to write a quicksort algorithm for [Int]

func swap(array:[Int], x:Int, y:Int)->[Int] {  //swap elements in array
    var result:[Int] = array
    result[y] = array[x]
    result[x] = array[y]
    return result
}

func split(array:[Int], u:Int, o:Int , p:Int)->Int {  //where the sorting happens
    let pivot:Int = array[p]
    swap(array: array, x: p, y: o)
    var pn:Int = u

    for j in u...o {
        if(array[j] <= pivot) {
        swap(array: array, x: pn, y: j)
        pn = pn+1
        }
    }
    swap(array: array, x: pn, y: o);
    return pn;
}

func quickSortR(array:[Int],u:Int ,o:Int) {  //recursive call
    if(u < o){
        let p:Int = o
        let pn:Int = split(array: array, u: u, o: o, p: p)
        quickSortR(array: array,u: u,o: pn-1)
        quickSortR(array: array,u: pn+1,o: o)
    }
}

func quickSort(array:[Int]) {  //initial call
    quickSortR(array: array, u: 0, o: array.count-1)
}

My problem is that I don't know how to apply this implementation on an array.

For example if I got the array a:[Int] = [3,1,2]. I can't check if the implementation is working by print(quickSort(a)), because the return type of quickSort is void. Of course I can't apply quickSort on that array like a.quickSort(a)

I really don't want to change my implementation of the algorithm by much if it isn't the cause of that problem (e.g. just the signature or return type)


Solution

  • Just improve your syntax:

    func swap(array: inout [Int], x:Int, y:Int) {  //swap elements in array
        let temp = array[x]
        array[x] = array[y]
        array[y] = temp
    }
    
    func split(array: inout [Int], u:Int, o:Int , p:Int) -> Int {  //where the sorting happens
        print(ar, u , o , p)
        let pivot:Int = array[p]
        swap(array: &array, x: p, y: o)
        var pn:Int = u
    
        for j in u..<o {
            if(array[j] <= pivot) {
                swap(array: &array, x: pn, y: j)
                pn = pn+1
            }
        }
        swap(array: &array, x: pn, y: o);
        return pn;
    }
    
    func quickSortR(array: inout [Int],u:Int ,o:Int) {  //recursive call
    
        if(u < o){
            let p:Int = o
            let pn:Int = split(array: &array, u: u, o: o, p: p)
    
            quickSortR(array: &array,u: u,o: pn-1)
            quickSortR(array: &array,u: pn+1,o: o)
        }
    }
    
    func quickSort(array: inout [Int]) {  //initial call
        quickSortR(array: &array, u: 0, o: array.count-1)
    }
    

    If you use func swap(array: [Int]) array is immutable inside the method. It just copies. Using inout resolves this problem.

    To check the code use somethink like this:

    var ar = [1]
    quickSort(array: &ar)
    print(ar)