Last active
August 29, 2018 02:23
-
-
Save 0xABCCBA/6791f1447367fa9e514435877fc5bc54 to your computer and use it in GitHub Desktop.
MergeSort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// https://www.raywenderlich.com/741-swift-algorithm-club-swift-merge-sort | |
/// divide and conquer | |
/// merge sort O(nlogn) | |
/// | |
/// - Parameter array: unsorted array | |
/// - Returns: sorted array | |
func mergeSort<T: Comparable>(_ array: [T]) -> [T] { | |
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<T: Comparable>(_ left: [T], _ right: [T]) -> [T] { | |
var leftIndex = 0 | |
var rightIndex = 0 | |
var orderedArray: [T] = [] | |
while leftIndex < left.count && rightIndex < right.count { | |
let leftElement = left[leftIndex] | |
let rightElement = right[rightIndex] | |
if leftElement < rightElement { | |
orderedArray.append(leftElement) | |
leftIndex += 1 | |
} else if leftElement > rightElement { | |
orderedArray.append(rightElement) | |
rightIndex += 1 | |
} else { | |
orderedArray.append(leftElement) | |
leftIndex += 1 | |
orderedArray.append(rightElement) | |
rightIndex += 1 | |
} | |
} | |
while leftIndex < left.count { | |
orderedArray.append(left[leftIndex]) | |
leftIndex += 1 | |
} | |
while rightIndex < right.count { | |
orderedArray.append(right[rightIndex]) | |
rightIndex += 1 | |
} | |
return orderedArray | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment