0

In Swift, everything is implemented as a struct rather than a class. Values are being passed in, but the memory address does not store them. Here is an example:

import UIKit


var array = Array<Int>()
array = [6,2,9,1,10,4,9,3,5,8,7]
let count = array.count

func insertSort(var arr : Array<Int>)->(){
for(var i = 1; i<arr.count-1; i++){
    var j : Int
    for( j = i; j > 0; j--){
        if(arr[j]<arr[j-1]){
            var temp = arr[j-1]
            var temp2 = arr[j]
            arr.removeAtIndex(j-1)
            arr.insert(temp2, atIndex: j-1)
            arr.removeAtIndex(j)
            arr.insert(temp, atIndex: j)
        }
    }
}
for item in arr{
    print(item)
}
}

insertSort(array)

array

I know that this isn't the most concise way to implement an insertion sort, but I was just trying to use the most Swift I could.

My issue: through the print statement in the function, I can see that the algorithm works - the list is returned sorted. However, when I print the array at the bottom, Playground returns the same array as the one I declared at the top, ie unsorted. I know why that is (the array is not implemented as a class), I just wanted to know if there is a way to fix it.

1 Answer 1

2

To modify a value type passed to a function, you need to pass it as an inout parameter:

func insertSort(inout arr: [Int]) {
    // etc.
}

insertSort(&array)

This is how Swift.sort is declared – try cmd-opt-clicking it in a playground or take a look at the Swifter docs.

inout should be used sparingly – one of the big benefits of structs is that they can be declared immutable with let, but immutable structs cannot be passed as inout parameters. This is why the standard library declares both sort, which takes an inout and sorts in-place, and sorted, which takes input by value and returns a freshly sorted array.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Of course I would normally use the given sort, but if it's like Java (mergesort) then I may want to use a faster sorting algorithm depending on the input.
Swift’s sort is as of 1.1 an introsort (which is a hybrid between a quicksort and a heapsort), but with insertion sort for small input ranges. This is as shown by sticking a breakpoint on a custom less-than operator, but it’s undocumented so not guaranteed to stay this way. The docs do state it’s unstable, which would have made merge sort unlikely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.