Created
January 3, 2017 01:06
-
-
Save ChenCodes/18e38c129fd008069ee1f696c903ee05 to your computer and use it in GitHub Desktop.
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
func mergeSort(_ array: [Int]) -> [Int] { | |
guard array.count > 1 else { return array } // 1 | |
let middleIndex = array.count / 2 // 2 | |
let leftArray = mergeSort(Array(array[0..<middleIndex])) // 3 | |
let rightArray = mergeSort(Array(array[middleIndex..<array.count])) // 4 | |
return merge(leftPile: leftArray, rightPile: rightArray) // 5 | |
} | |
func merge(leftPile: [Int], rightPile: [Int]) -> [Int] { | |
// 1 | |
var leftIndex = 0 | |
var rightIndex = 0 | |
// 2 | |
var orderedPile = [Int]() | |
// 3 | |
while leftIndex < leftPile.count && rightIndex < rightPile.count { | |
if leftPile[leftIndex] < rightPile[rightIndex] { | |
orderedPile.append(leftPile[leftIndex]) | |
leftIndex += 1 | |
} else if leftPile[leftIndex] > rightPile[rightIndex] { | |
orderedPile.append(rightPile[rightIndex]) | |
rightIndex += 1 | |
} else { | |
orderedPile.append(leftPile[leftIndex]) | |
leftIndex += 1 | |
orderedPile.append(rightPile[rightIndex]) | |
rightIndex += 1 | |
} | |
} | |
// 4 | |
while leftIndex < leftPile.count { | |
orderedPile.append(leftPile[leftIndex]) | |
leftIndex += 1 | |
} | |
while rightIndex < rightPile.count { | |
orderedPile.append(rightPile[rightIndex]) | |
rightIndex += 1 | |
} | |
return orderedPile | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment