Skip to content

Assignment 1 - Selection Sort #2

Open
@gmertk

Description

@gmertk

When you ask someone to sort a list of numbers in ascending order, you will see that the common intuition will be like "Select the minimum card and put it in the first place. Select the second minimum and put it in the second place. And so on". This is called selection sort.

  1. Write a selectionSort function that takes an integer array and returns it as sorted in ascending order. Don't mutate the original array (don't use inout). Note that there is already a swap function in the standard library. When using the swap, you need to guard it from swapping a location with itself.
  2. Turn the function into a generic function so that it can sort any type of array. Only constraint is that elements of the array should conform to the Comparable protocol.
  3. Instead of sorting the array in ascending order, modify your function to accept a closure that takes two arguments of the same type as the array’s contents, and returns Bool. You can name this closure parameter isOrderedBefore (as in sort function of the standard library). Check what @noescape means in Swift. Also you now use another function to do the comparison, you can remove the Comparable constraint.
  4. Instead of only sorting arrays, modify your function to sort any type conforming to SequenceType. Make your function to be an extension of SequenceType so that we can use it as [1, 3, 2].selectionSort(<) and [1: "b", 2: "a"].selectionSort {$0.0 > $1.0}.

Due Date: Next Wednesday 25.11.2015

Next assignment will be about writing an insertion sort (as you guessed). Feel free to send comments 😄

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions