alman williams algorithm in swift

Here's a sample implementation of the Alman-Williams algorithm in Swift:

main.swift
func mergeSort(_ array: [Int]) -> [Int] {
    guard array.count > 1 else { return array }
    let middleIndex = array.count / 2
    let leftArray = mergeSort(Array(array[0..<middleIndex]))
    let rightArray = mergeSort(Array(array[middleIndex..<array.count]))
    return merge(leftArray, rightArray)
}

func merge(_ left: [Int], _ right: [Int]) -> [Int] {
    var leftIndex = 0, rightIndex = 0
    var resultArray = [Int]()
    while leftIndex < left.count && rightIndex < right.count {
        if left[leftIndex] < right[rightIndex] {
            resultArray.append(left[leftIndex])
            leftIndex += 1
        } else {
            resultArray.append(right[rightIndex])
            rightIndex += 1
        }
    }
    return resultArray + Array(left[leftIndex..<left.count]) + Array(right[rightIndex..<right.count])
}
827 chars
23 lines

The mergeSort function uses a divide-and-conquer approach to recursively split the input array into halves, and then merge them back together while sorting the merged result. The merge function is used to actually merge the left and right sub-arrays, sorting them in the process. To use the algorithm, simply call mergeSort with an array of integers.

gistlibby LogSnag