n*logn
function mergeSort(arr) {
if (arr.length < 2) {
return arr
} else {
const mid = Math.floor(arr.length / 2)
const left = arr.slice(0, mid)
const right = arr.slice(mid)
return merge(mergeSort(left), mergeSort(right))
}
}
function merge(left, right) {
const result = []
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift())
} else {
result.push(right.shift())
}
}
while (left.length) result.push(left.shift())
while (right.length) result.push(right.shift())
return result
}
YOUTUBE | 2015 봄학기 알고리즘 | 권오흠
합병(머지, 병합) 정렬 by.zerocho
Photo by Michael Dziedzic on Unsplash