sort list with mergesort in swift

Here is an implementation of Merge Sort to sort a list of integers in ascending order using Swift programming language:

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
    var rightIndex = 0
    var orderedArray: [Int] = []
    
    while leftIndex < left.count && rightIndex < right.count {
        if left[leftIndex] < right[rightIndex] {
            orderedArray.append(left[leftIndex])
            leftIndex += 1
        } else if left[leftIndex] > right[rightIndex] {
            orderedArray.append(right[rightIndex])
            rightIndex += 1
        } else {
            orderedArray.append(left[leftIndex])
            leftIndex += 1
            orderedArray.append(right[rightIndex])
            rightIndex += 1
        }
    }
    
    while leftIndex < left.count {
        orderedArray.append(left[leftIndex])
        leftIndex += 1
    }
    
    while rightIndex < right.count {
        orderedArray.append(right[rightIndex])
        rightIndex += 1
    }
    
    return orderedArray
}
1237 chars
45 lines

To use this implementation, simply call mergeSort function with an array of integers as its parameter:

main.swift
let unsortedArray = [10, 5, 2, 4, 7, 8, 3, 1, 6, 9]
let sortedArray = mergeSort(unsortedArray)
print(sortedArray) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
149 chars
4 lines

This implementation first divides the given array into two halves (left and right) until each half contains only one element or less. Then, it recursively calls itself on the left and right halves until all of the elements are sorted. Finally, it merges the sorted left and right halves.

gistlibby LogSnag