diff --git a/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift b/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift index 98fc641..6696730 100644 --- a/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift +++ b/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift @@ -6,10 +6,30 @@ Write an `insertionSort` function that takes an array and returns it as sorted b Note that there is already a `swap` function in the standard library. However, you can move the larger elements to the right rather than using the `swap` function. */ +extension Array { + func insertInOrder(newElement: Element, @noescape isOrderedBefore: (Element, Element) -> Bool) -> [Element] { + var array = self + guard !array.isEmpty else { + return [newElement] + } + + let firstElement = array.removeFirst() + if isOrderedBefore(newElement, firstElement) { + return [newElement, firstElement] + array + } else { + return [firstElement] + array.insertInOrder(newElement, isOrderedBefore: isOrderedBefore) + } + } +} func insertionSort(var array: [T], @noescape isOrderedBefore: (T, T) -> Bool) -> [T] { - - return array + guard !array.isEmpty else { + return [] + } + + let firstElement = array.removeFirst() // this removes the first element from the array mutating it + let subOrderedArray = insertionSort(array, isOrderedBefore: isOrderedBefore) // recursive call on the smaller array + return subOrderedArray.insertInOrder(firstElement, isOrderedBefore: isOrderedBefore) // insert the first element mainting the order in the subarray, which is ordered } @@ -22,8 +42,8 @@ assert(items == ["c", "d", "b"]) // double check that items does not change assert(insertionSort([1], isOrderedBefore: <).isSorted()) assert(insertionSort([1, 2, 3], isOrderedBefore: <).isSorted()) -//assert(insertionSort([1, 2, 3], isOrderedBefore: >).isSorted(>)) -//assert(insertionSort([3, 2, 1, 2, -1], isOrderedBefore: <).isSorted()) +assert(insertionSort([1, 2, 3], isOrderedBefore: >).isSorted(>)) +assert(insertionSort([3, 2, 1, 2, -1], isOrderedBefore: <).isSorted()) /*: [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)