sorting algorithms in node js

Solutions on MaxInterview for sorting algorithms in node js by the best coders in the world

showing results for - "sorting algorithms in node js"
Oonagh
29 Feb 2020
1function sort(arr, compareFn = (a, b) => a <= b) {
2
3    if (!arr instanceof Array || arr.length === 0) {
4        return arr;
5    }
6
7    if (typeof compareFn !== 'function') {
8        throw new Error('compareFn is not a function!');
9    }
10
11    const partition = (arr, low, high) => {
12        const pivot = arr[low];
13        while (low < high) {
14            while (low < high && compareFn(pivot, arr[high])) {
15                --high;
16            }
17            arr[low] = arr[high];
18            while (low < high && compareFn(arr[low], pivot)) {
19                ++low;
20            }
21            arr[high] = arr[low];
22        }
23        arr[low] = pivot;
24        return low;
25    };
26
27    const quickSort = (arr, low, high) => {
28        if (low < high) {
29            let pivot = partition(arr, low, high);
30            quickSort(arr, low, pivot - 1);
31            quickSort(arr, pivot + 1, high);
32        }
33        return arr;
34    };
35
36    return quickSort(arr, 0, arr.length - 1);
37}