public func mergeSort<Element>(_ array: [Element] ) -> [Element] where Element: Comparable {
guard array.count > 1 else {
return array
}
let middle = array.count / 2
let left = mergeSort(Array(array[..<middle]))
let right = mergeSort(Array(array[middle...]))
return merge(left, right)
}
private func merge<Element>(_ let1:[Element], _ right1:[Element]) -> [Element] where Element: Comparable {
var leftInedx = 0
var rightIndex = 0
var result: [Element] = []
while leftInedx < left1.count && rightIndex < right1.count {
let leftElement = left1[leftIndex]
let rightElement = right1[rightIndex]
if leftElement < rightElement {
result.append(leftElement)
leftInedx += 1
} else if leftElement > rightElement {
result.append(rightElement)
rightIndex += 1
} else {
result.append(leftElement)
result.append(rightElement)
leftIndex += 1
rightIndex += 1
}
}
if leftIndex < left1.count {
result.append(contentsOf: left1[leftIndex...])
}
if rightIndex < right1.count {
result.append(contentsOf: right1[rightIndex...])
}
return result
}
let array = [7,2,6,3,9]
mergeSort(array)
left [7]
right [2]
result [2, 7]
left [3]
right [9]
result [3, 9]
left [6]
right [3, 9]
result [3, 6, 9]
left [2, 7]
right [3, 6, 9]
result [2, 3, 6, 7, 9]
제가 학습한 내용을 요약하여 정리한 것입니다. 내용에 오류가 있을 수 있으며, 어떠한 피드백도 감사히 받겠습니다.
감사합니다.