Chalarangelo/30-seconds-of-code

Another quicksort implementation

yunielrc opened this issue · 1 comments

More compact and easy to understand but slower

const quicksort = arr =>
  arr.length <= 1
    ? arr
    : [
        ...quicksort(arr.slice(1).filter((el) => el < arr[0])),
        arr[0],
        ...quicksort(arr.slice(1).filter((el) => el >= arr[0])),
      ];

The Fastest implementation

const quickSort = array =>
  (function qsort(arr, start, end) {
    if (start >= end) return arr;
    let swapPos = start;

    for (let i = start; i <= end; i++) {
      if (arr[i] <= arr[end]) {
        [arr[swapPos], arr[i]] = [arr[i], arr[swapPos]];
        swapPos++;
      }
    }
    qsort(arr, start, --swapPos - 1);
    qsort(arr, swapPos + 1, end);

    return arr;
  })([...array], 0, array.length - 1);

Thanks for the suggestion, but the current implementation is fine as-is and is polished to balance readability, reasonable performance and introduction of JS concepts.