[Algorithms] Quicksort algorithm using TypeScript
Quicksort (also called partition sort and pivot sort) is arguably the most used sorting algorithm. It is the one commonly implemented internally in language runtimes. In this lesson we cover the quick sort algorithm, why is it called quick and how to implement it using TypeScript / JavaScript.
function partition(arr: number[], low: number, high: number): number {
const pivot = arr[high];
let idx = low - 1;
for (let i = low; i < high; i++) {
if (arr[i] <= pivot) {
idx++;
const temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
}
// swap pivot to its correct position
idx++;
arr[high] = arr[idx];
arr[idx] = pivot;
return idx;
}
function qs(arr: number[], low: number, high: number): void {
if (low >= high) {
return;
}
const pivotIdx = partition(arr, low, high);
qs(arr, low, pivotIdx - 1);
qs(arr, pivotIdx + 1, high);
}
export default function quick_sort(arr: number[]): void {
qs(arr, 0, arr.length - 1);
}
Test:
import quick_sort from "@code/QuickSort";
test("quick-sort", function () {
const arr = [9, 3, 7, 4, 69, 420, 42];
debugger;
quick_sort(arr);
expect(arr).toEqual([3, 4, 7, 9, 42, 69, 420]);
});