From bd1499ab6623ddcdb6efe5c9d82ad7344eed7e78 Mon Sep 17 00:00:00 2001 From: NithinNara Date: Sun, 29 Nov 2015 22:59:08 +0530 Subject: [PATCH] Assigment-2 Insertion Sort Solution --- .../Contents.swift | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) 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..764e342 100644 --- a/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift +++ b/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift @@ -8,7 +8,19 @@ Note that there is already a `swap` function in the standard library. However, y */ func insertionSort(var array: [T], @noescape isOrderedBefore: (T, T) -> Bool) -> [T] { - + + guard array.count > 1 else { + return array + } + + for index in 1.. 0 && !isOrderedBefore(array[j-1], array[j]) { + swap(&array[j], &array[j-1]) + j-- + } + } + return array } @@ -17,13 +29,13 @@ func insertionSort(var array: [T], @noescape isOrderedBefore: (T, T) -> Bool) let items = ["c", "d", "b"] let sortedItems = insertionSort(items, isOrderedBefore: <) -//assert(sortedItems.isSorted()) +assert(sortedItems.isSorted(<)) 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)