Master the divide-and-conquer approach with Quicksort and Merge Sort. Learn how these efficient algorithms tackle complex sorting problems.
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int pivotIndex = partition(arr, left, right);
quickSort(arr, left, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, right);
}
}
private static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[right];
arr[right] = temp;
return i + 1;
}
public static int[] mergeSort(int[] arr) {
if (arr.length <= 1) return arr;
int mid = arr.length / 2;
int[] left = Arrays.copyOfRange(arr, 0, mid);
int[] right = Arrays.copyOfRange(arr, mid, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
private static int[] merge(int[] left, int[] right) {
int[] result = new int[left.length + right.length];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result[k++] = left[i++];
} else {
result[k++] = right[j++];
}
}
while (i < left.length) {
result[k++] = left[i++];
}
while (j < right.length) {
result[k++] = right[j++];
}
return result;
}
int[] arr1 = {64, 34, 25, 12, 22, 11, 90};
quickSort(arr1, 0, arr1.length - 1);
System.out.println("Quicksort: " + Arrays.toString(arr1));
int[] arr2 = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Merge sort: " + Arrays.toString(mergeSort(arr2)));
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.