Shorthand in Swift -
so i'm going through "a swift tour" tutorial @ 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 @ section sort/shorthand. example given
sort([1, 5, 3, 12, 2]) { $0 > $1 }
i println'd closure see happening , here got:
the $0 5 , $1 1 $0 3 , $1 5 $0 3 , $1 1 $0 12 , $1 5 $0 2 , $1 12 $0 2 , $1 5 $0 2 , $1 3 $0 2 , $1 1
on first line, notice $1 1 while $0 5. question why isn't number "1" assigned $0 (rather $1) since falls first in array. understand algorithm , all...it's shorthand attribution bothering me. guess it's nickpicky, if can clear me, appreciate it!
this has nothing shorthand, it's optimisation in internal implementation of sorting. doesn't matter order arguments passed closure, internally they'll passed in whatever order happens efficient.
looking @ order of comparisons, looks happening insertion sort - common algorithm small data sets, quicksort being selected above list length.
as can see when 2 processed @ end, insertion sort takes each new element, , walks through sorted data find correct position. such, $0 selected first, $1 set each existing element in turn.
at beginning of algorithm, there no comparisons made, 1 never placed $0 slot. first comparison needed has new element 5, existing element 1.
Comments
Post a Comment