guy8214
guy8214

Reputation: 1115

Shorthand in Swift

So I'm currently going through the "A Swift Tour" tutorial at the Apple site. (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-XID_1)

My confusion comes at the section for Sort/Shorthand. The example given is

sort([1, 5, 3, 12, 2]) { $0 > $1 }

I println'd the closure to see what was happening and here is what I got:

The $0 is 5 and the $1 is 1
The $0 is 3 and the $1 is 5
The $0 is 3 and the $1 is 1
The $0 is 12 and the $1 is 5
The $0 is 2 and the $1 is 12
The $0 is 2 and the $1 is 5
The $0 is 2 and the $1 is 3
The $0 is 2 and the $1 is 1

On the first line, notice that $1 is 1 while $0 is 5. My question is why isn't the number "1" assigned as $0 (rather than $1) since it falls first in the array. I understand the algorithm and all...it's just the shorthand attribution that is bothering me. I guess it's nickpicky, but if anyone can clear this up for me, I would greatly appreciate it!

Upvotes: 2

Views: 715

Answers (1)

IMSoP
IMSoP

Reputation: 97718

This has nothing to do with the shorthand, it's just optimisation in the internal implementation of sorting. It doesn't matter which order the arguments are passed to the closure, so internally they'll be passed in whatever order happens to be efficient.

Looking at the order of comparisons, it looks like what is happening is an insertion sort - a common algorithm for small data sets, with quicksort usually being selected above a certain list length.

As you can see when the 2 is processed at the end, an insertion sort takes each new element, and walks through the sorted data to find its correct position. As such, $0 is selected first, then $1 is set to each existing element in turn.

At the very beginning of the algorithm, there are no comparisons to be made, so 1 is never placed into the $0 slot. The first comparison needed has new element 5, existing element 1.

Upvotes: 7

Related Questions