📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
- Divide the list into sub list of about half size in each iteration until each sublist has only one element.
- Merge each sublist repeatedly to create a sorted list. It will run until we have only 1 sorted list. This will be the sorted list.
How the Merge Sort Works?
10 15 20 21 23 25 30 65
Merge Sort Algorithm in JavaScript
function mergeSort(array, compareFn = defaultCompare) {
if (array.length > 1) {
const {
length
} = array;
const middle = Math.floor(length / 2);
const left = mergeSort(array.slice(0, middle), compareFn);
const right = mergeSort(array.slice(middle, length), compareFn);
array = merge(left, right, compareFn);
}
return array;
}
const Compare = {
LESS_THAN: -1,
BIGGER_THAN: 1,
EQUALS: 0
};
function merge(left, right, compareFn) {
let i = 0;
let j = 0;
const result = [];
while (i < left.length && j < right.length) {
result.push(compareFn(left[i], right[j]) === Compare.LESS_THAN ? left[i++] : right[j++]);
}
return result.concat(i < left.length ? left.slice(i) : right.slice(j));
}
function defaultCompare(a, b) {
if (a === b) {
return Compare.EQUALS;
}
return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN;
}
Using Merge Sort Algorithm
const array1 = [20, 23, 25, 21, 30, 10, 65, 15];
const array2 = mergeSort(array1);
console.log(array2);
Output
[10, 15, 20, 21, 23, 25, 30, 65]
Comments
Post a Comment
Leave Comment