Visualize the Merge Sort algorithm, a classic example of Divide and Conquer.
Enter an array and click 'Start Sort' to begin.
Merge Sort follows the Divide and Conquer paradigm:
function mergeSort(arr) {
if (arr.length <= 1) {
return arr; // Base case: array is already sorted
}
// Divide
const mid = Math.floor(arr.length / 2);
const leftHalf = arr.slice(0, mid);
const rightHalf = arr.slice(mid);
// Conquer (Recursive calls)
const sortedLeft = mergeSort(leftHalf);
const sortedRight = mergeSort(rightHalf);
// Combine (Merge)
return merge(sortedLeft, sortedRight);
}
function merge(left, right) {
let result = [];
let leftIndex = 0;
let rightIndex = 0;
// Compare elements and add the smaller one to the result
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
// Add any remaining elements from left or right subarray
return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
}