Created
October 5, 2024 12:27
-
-
Save mshossain110/a6e2acad17995989fe1573a4aa779b0f to your computer and use it in GitHub Desktop.
Merge Sort Using JavaScript
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
var unsortedArr = [10, 55, 20, 4, 28, 69, 22, 85, 7, 37]; | |
function merge( arr, left, mid, right) | |
{ | |
const n1 = mid - left + 1 | |
const n2 = right - mid; | |
const LA = new Array(n1); | |
const RA = new Array(n2); | |
for(let i = 0; i< n1; i++) | |
LA[i] = arr[left + i]; | |
for(let j = 0; j < n2; j++) | |
RA[j] = arr[mid +j + 1]; | |
let i = j = 0 | |
let k = left; | |
while(i < n1 && j < n2) { | |
if (LA[i] < RA[j]){ | |
arr[k] = LA[i]; | |
i++; | |
} else { | |
arr[k] = RA[j]; | |
j++; | |
} | |
k++; | |
} | |
while (i<n1) { | |
arr[k] = LA[i]; | |
i++; | |
k++; | |
} | |
while (j<n2) { | |
arr[k] = RA[j]; | |
j++; | |
k++; | |
} | |
} | |
function mergeSort(arr, left, right) | |
{ | |
if (left >= right) | |
return; | |
const mid = Math.floor(left + (right - left) / 2); | |
mergeSort(arr, left, mid); | |
mergeSort(arr, mid + 1, right); | |
merge(arr, left, mid, right); | |
return arr; | |
} | |
console.log(mergeSort(unsortedArr, 0, unsortedArr.length - 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Merge Sort
Description: Divides the array into halves, recursively sorts them, and then merges the sorted halves.
Time Complexity: O(n log n)
Use Case: Efficient for large datasets, uses additional space for merging.