SortMethod

protocol SortMethod

A common protocol for all sorting methods.

Note that the array to be sorted is hosted in an external object, and provided to the sorting methods as a parameter to the nextStep() method. Each execution of the nextStep() executes one relevant step of the sorting algorithm, usually leading into values changing places in the array to be sorted. This can then be animated in the UI.

Protocol implementations must also implement realAlgorithm(), executing the sorting method in a tight loop. This is not animated in the UI, but used in comparing the speed of the algorithms.

Note that when giving an array to be sorted to various sorting methods, the array each of them starts with must contain the same numbers in the same order – otherwise the comparisons are not fair.

  • Initializes the sortmethod to sort an array with specific number of elements.

    Declaration

    Swift

    init(arraySize: Int)

    Parameters

    arraySize

    The size of the array to initialize.

  • The size of the array to sort.

    Declaration

    Swift

    var size: Int { get }
  • The name of the sorting method. Should return a short descriptive name, like “BubbleSort”.

    Declaration

    Swift

    var name: String { get }
  • A 2-3 sentence description of the sorting method.

    Declaration

    Swift

    var description: String { get }
  • A collection of a description and a link to a website with more information about the sort method.

    Declaration

    Swift

    var webLinks: [(String, String)] { get }
  • Restarts the sorting by resetting all loop counters, etc.

    Declaration

    Swift

    mutating func restart()
  • Does the next step in the sort, moving or switching two values in the array. Caller will do the actual swapping of values in the array.

    This method is called repeatedly until it returns true. After each step, the UI is updated to visualize the process of sorting.

    Note that caller should have swappedItems as a local variable within a loop so that it is resetted before each call to nextStep.

    Declaration

    Swift

    mutating func nextStep(array: [Int], swappedItems: inout SwappedItems) -> Bool

    Return Value

    Returns true if the array is sorted. Caller should stop sorting (calling nextStep).

  • Implementation of the sorting method without any steps, sorting the data in one go in a loop/loops. The caller should verify if the array is actually sorted properly by doing assert(Array.isSorted()) when this function returns.

    Declaration

    Swift

    mutating func realAlgorithm(array: inout [Int])

    Parameters

    array

    The array to sort.