[swift-users] Simplify chained calls

Dan Loewenherz dan at lionheartsw.com
Wed Jun 29 00:42:22 CDT 2016


On Tue, Jun 28, 2016 at 9:58 PM, Erica Sadun <erica at ericasadun.com> wrote:

> Most everyone is doing two passes, one to get the minimum value, another
> to get its index.
> I aesthetically prefer using enumerate to do both at once.
>
> -- E
>

Makes sense. Here’s a revision. It’s not as simple, but it does just one
pass through the array:


func selectionSort(_ array: [Int]) -> [Int] {

    guard let first = array.first else { return [] }

    let (index, minValue) = array.enumerated().reduce((0, first)) { (carry,
item) in

        if item.element < carry.1 { return item } else { return carry }

    }


    let ranges = [0..<index, index.advanced(by: 1)..<array.endIndex]

    return [minValue] + selectionSort(ranges.flatMap { array[$0] })

}

~Dan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160629/e3ca2568/attachment.html>


More information about the swift-users mailing list