반응형
Merge Sort
function mergeSort(arr) {
if(arr.length <= 1) return arr;
let mid = Math.floor(arr.length/2);
let left = mergeSort(arr.slice(0, mid));
let right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(arr1, arr2) {
let results = [];
let i = 0;
let j = 0;
while (i < arr.length && j < arr2.length) {
if(arr2[j] > arr1[i]) {
results.push(arr1[i]);
i++;
} else {
results.push(arr2[j])
j++;
}
}
while (i < arr.length) {
results.push(arr1[i])
i++;
}
while(j < arr2.length) {
results.push(arr2[j])
j++;
}
return results;
}
반응형
'코어 > 자료구조 & 알고리즘' 카테고리의 다른 글
[JavaScript 알고리즘] 정렬(Sorting) - 6. Radix Sort (0) | 2021.06.11 |
---|---|
[JavaScript 알고리즘] 정렬(Sorting) - 5. Quick Sort (0) | 2021.06.11 |
[JavaScript 알고리즘] 정렬(Sorting) - 3. Insertion Sort (0) | 2021.06.11 |
[JavaScript 알고리즘] 정렬(sorting) - 2. Selection Sort (0) | 2021.06.10 |
[JavaScript 알고리즘] 정렬(sorting) - 1. Bubble Sort (0) | 2021.06.10 |