sorting algorithm in javascript code example

Example 1: what is the algorithm for javascript array.sort

function bubbleSort(arr){
   var len = arr.length;
   for (var i = len-1; i>=0; i--){
     for(var j = 1; j<=i; j++){
       if(arr[j-1]>arr[j]){
           var temp = arr[j-1];
           arr[j-1] = arr[j];
           arr[j] = temp;
        }
     }
   }
   return arr;
}
bubbleSort([7,5,2,4,3,9]); //[2, 3, 4, 5, 7, 9]
bubbleSort([9,7,5,4,3,1]); //[1, 3, 4, 5, 7, 9]
bubbleSort([1,2,3,4,5,6]); //[1, 2, 3, 4, 5, 6]

Example 2: sorting in js

var arr = [23, 34343, 1, 5, 90, 9]

//using forEach
var sortedArr = [];
arr.forEach(x => {
    if (sortedArr.length == 0)
        sortedArr.push(x)
    else {
        if (sortedArr[0] > x) sortedArr.unshift(x)
        else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
        else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
    }
})
console.log(sortedArr);


// using sort method
console.log(arr.sort((a,b)=>{
    return a-b;
}));

Example 3: sorting algorithms in node.js

function sort(arr, compareFn = (a, b) => a <= b) {

    if (!arr instanceof Array || arr.length === 0) {
        return arr;
    }

    if (typeof compareFn !== 'function') {
        throw new Error('compareFn is not a function!');
    }

    const partition = (arr, low, high) => {
        const pivot = arr[low];
        while (low < high) {
            while (low < high && compareFn(pivot, arr[high])) {
                --high;
            }
            arr[low] = arr[high];
            while (low < high && compareFn(arr[low], pivot)) {
                ++low;
            }
            arr[high] = arr[low];
        }
        arr[low] = pivot;
        return low;
    };

    const quickSort = (arr, low, high) => {
        if (low < high) {
            let pivot = partition(arr, low, high);
            quickSort(arr, low, pivot - 1);
            quickSort(arr, pivot + 1, high);
        }
        return arr;
    };

    return quickSort(arr, 0, arr.length - 1);
}