gistlib
Here's an implementation of the Quicksort algorithm in JavaScript, using the Hoare partition scheme:
index.tsxfunction quickSort(arr, left = 0, right = arr.length - 1) { if (left >= right) { return; } const pivot = arr[left + Math.floor((right - left) / 2)]; const index = partition(arr, left, right, pivot); quickSort(arr, left, index - 1); quickSort(arr, index, right); return arr; } function partition(arr, left, right, pivot) { while (left <= right) { while (arr[left] < pivot) { left++; } while (arr[right] > pivot) { right--; } if (left <= right) { [arr[left], arr[right]] = [arr[right], arr[left]]; left++; right--; } } return left; } 618 chars35 lines
function quickSort(arr, left = 0, right = arr.length - 1) { if (left >= right) { return; } const pivot = arr[left + Math.floor((right - left) / 2)]; const index = partition(arr, left, right, pivot); quickSort(arr, left, index - 1); quickSort(arr, index, right); return arr; } function partition(arr, left, right, pivot) { while (left <= right) { while (arr[left] < pivot) { left++; } while (arr[right] > pivot) { right--; } if (left <= right) { [arr[left], arr[right]] = [arr[right], arr[left]]; left++; right--; } } return left; }
To use it, simply call quickSort with the array as the first argument:
quickSort
index.tsxconst arr = [5, 2, 6, 1, 3, 9]; quickSort(arr); // [1, 2, 3, 5, 6, 9] 70 chars3 lines
const arr = [5, 2, 6, 1, 3, 9]; quickSort(arr); // [1, 2, 3, 5, 6, 9]
gistlibby LogSnag