Master the divide-and-conquer approach with Quicksort and Merge Sort. Learn how these efficient algorithms tackle complex sorting problems.
function quickSort(arr, left = 0, right = arr.length - 1) {
if (left < right) {
const pivotIndex = partition(arr, left, right);
quickSort(arr, left, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, right);
}
return arr;
}
function partition(arr, left, right) {
const pivot = arr[right];
let i = left - 1;
for (let j = left; j < right; j++) {
if (arr[j] <= pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[right]] = [arr[right], arr[i + 1]];
return i + 1;
}
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) {
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result.push(left[i++]);
} else {
result.push(right[j++]);
}
}
return result.concat(left.slice(i)).concat(right.slice(j));
}
const arr1 = [64, 34, 25, 12, 22, 11, 90];
console.log('Quicksort:', quickSort([...arr1]));
console.log('Merge sort:', mergeSort([...arr1]));
Implement a hybrid sorting algorithm that uses both Quicksort and Insertion Sort.
Extend the merge sort algorithm to handle k sorted arrays simultaneously.
const arrays = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
];
console.log(kWayMerge(arrays));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Modify both sorting algorithms to work with custom comparison functions.
const people = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
];
// Sort by age
quickSort(people, (a, b) => a.age - b.age);
// Sort by name
mergeSort(people, (a, b) => a.name.localeCompare(b.name));
The following LeetCode problems are excellent resources for practicing sorting algorithms and preparing for technical interviews.
Note: Previously, this course referenced the CodeSignal Arcade, which is no longer available. The LeetCode problems above follow the same principles and are an excellent alternative for practicing sorting algorithms and preparing for technical interviews.