From 1b50eb4c44e4a6d12d0c9d42cbd26fc472574178 Mon Sep 17 00:00:00 2001 From: Alexandre Camilleri Date: Tue, 1 Dec 2015 16:34:44 +0100 Subject: [PATCH] Assignment 2 --- .../Contents.swift | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 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..134f65a 100644 --- a/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift +++ b/Assignments/Sorting/InsertionSort.playground/Pages/Insertion Sort.xcplaygroundpage/Contents.swift @@ -8,22 +8,28 @@ 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] { - + for var i1 = 0; i1 < array.count; ++i1 { + for var i2 = 0; i2 < array.count; ++i2 { + if i1 != i2 { + if isOrderedBefore(array[i1], array[i2]) { + swap(&array[i1], &array[i2]) + } + } + } + } return array } - - //: Test your function with assert. Make sure asserts don't raise any errors. `isSorted` is already defined for you in `Sources/Utilities.swift`. You can add more test cases. 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)