diff --git a/SortingAlgorithms/mergeSort.js b/SortingAlgorithms/mergeSort.js new file mode 100644 index 0000000..fa5a104 --- /dev/null +++ b/SortingAlgorithms/mergeSort.js @@ -0,0 +1,35 @@ +function mergeSort(arr) { + if (arr.length <= 1) { + return arr; + } + + const mid = Math.floor(arr.length / 2); + const left = mergeSort(arr.slice(0, mid)); + const right = mergeSort(arr.slice(mid)); + + return merge(left, right); +} + +function merge(left, right) { + let result = []; + let leftIndex = 0; + let rightIndex = 0; + + while (leftIndex < left.length && rightIndex < right.length) { + if (left[leftIndex] < right[rightIndex]) { + result.push(left[leftIndex]); + leftIndex++; + } else { + result.push(right[rightIndex]); + rightIndex++; + } + } + + // Concat remaining elements + return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)); +} + +// Example usage +const arr = [38, 27, 43, 3, 9, 82, 10]; +const sortedArray = mergeSort(arr); +console.log(sortedArray);