Last active
April 3, 2022 13:00
-
-
Save tetsuok/7e2154fdbfd73184dbfe27508f3c09e3 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
'use strict'; | |
// 与えられた配列を昇順にマージソートでソートした配列を返す. | |
function mergeSort(array) { | |
if (array.length <= 1) { | |
return array; | |
} | |
const mid = Math.floor(array.length / 2); | |
const a = array.slice(0, mid); // array[0:mid] | |
const b = array.slice(mid); // array[mid:] | |
return merge(mergeSort(a), mergeSort(b)); | |
} | |
// 2つの配列a, bの要素を小さい順に取り出して並べた配列を返す. | |
function merge(a, b) { | |
const result = []; | |
for (let i = 0, j = 0; i < a.length || j < b.length; ) { | |
if (i === a.length) { | |
result.push(b[j]); | |
j++; | |
continue; | |
} else if (j === b.length) { | |
result.push(a[i]); | |
i++; | |
continue; | |
} | |
if (a[i] <= b[j]) { | |
result.push(a[i]); | |
i++; | |
} else { | |
result.push(b[j]); | |
j++; | |
} | |
} | |
return result; | |
} | |
console.log('sorted', mergeSort([])); | |
console.log('sorted', mergeSort([1])); | |
console.log('sorted', mergeSort([2, 1])); | |
console.log('sorted', mergeSort([1, 3, 2])); | |
console.log('sorted', mergeSort([1, 2, 3])); | |
console.log('sorted', mergeSort([1, 3, 2, 3])); // 重複があるケース |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment