[swift-users] Simplify chained calls

Tod Cunningham tcunningham at vectorform.com
Wed Jun 29 18:12:51 CDT 2016


Was trying to using some functional programming concepts while also using as little memory as possible.  The big advantage of using a selections sort is that it sorts w/o having to allocation additional memory.  This still violates that, but it’s closer.  :)

func selectionSort(_ array: inout [Int]) {
    for index in 0..<array.count {
        // .1 is value .0 is the index on the enumeration
        let minElement = array.enumerated().dropFirst(index).min(isOrderedBefore: { $0.1 < $1.1 } )
        if index != minElement!.0 {
            swap(&array[index], &array[minElement!.0])
        }
    }
}

or using recursion:

func selectionSort(_ array: inout [Int], index: Int = 0) {
    if index < array.count {
        // .1 is value .0 is the index on the enumeration
        let minElement = array.indexed().dropFirst(index).min(isOrderedBefore: { $0.1 < $1.1 } )
        if index != minElement!.0 {
            swap(&array[index], &array[minElement!.0])
        }
        selectionSort(&array, index: index+1)
    }
}



On 6/28/16, 10:58 PM, "swift-users-bounces at swift.org on behalf of Erica Sadun via swift-users" <swift-users-bounces at swift.org on behalf of swift-users at swift.org> wrote:

> 
> On Jun 28, 2016, at 8:18 PM, Dan Loewenherz via swift-users <swift-users at swift.org> wrote:
> 
> I’m not sure if you wanted to stick with the pure functional approach, but here’s an alternative that uses Range<Int> to take care of most of the work.
> 
> func selectionSort(_ array: [Int]) -> [Int] {
>     guard let minValue = array.min(), let index = array.index(of: minValue) else {
>         return []
>     }
> 
>     let ranges = [0..<index, index.advanced(by: 1)..<array.endIndex]
>     return [minValue] + selectionSort(ranges.flatMap { array[$0] })
> }
> 

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

_______________________________________________
swift-users mailing list
swift-users at swift.org
https://lists.swift.org/mailman/listinfo/swift-users




More information about the swift-users mailing list