Sorting Algorithms in Javascript

This is just for quick reference does not really talk about CS theory for now.

let compare = (n1, n2) => n1 - n2; let bubbleSort = (arr, cmp = compare) => { for ( let i = 0 ; i < arr.length; i++) { for ( let j = i; j > 0 ; j--) { if (cmp(arr[j], arr[j - 1 ]) < 0 ) { [arr[j], arr[j - 1 ]] = [arr[j - 1 ], arr[j]]; } } } return arr; };

let insertionSort = (arr) => { for ( let i = 0 ; i < a.length; i++) { let toCmp = arr[i]; for ( let j = i; j > 0 && toCmp < a[j - 1 ]; j--) arr[j] = a[j - 1 ]; arr[j] = toCmp; } return arr; }

var selectionSort = function (arr) { let i,m,j; for (i = - 1 ; ++i < a.length;) { for (m = j = i; ++j < a.length;) { if (arr[m] > arr[j]) m = j; } [arr[m], arr[i]] = [arr[i], arr[m]]; } return arr; }

let mergeSort = (arr) => { if (arr.length < 2 ) return arr; let middle = parseInt (arr.length / 2 ), left = arr.slice( 0 , middle), right = arr.slice(middle); return merge(mergeSort(left), mergeSort(right)); } let merge = (left, right) => { let result = []; while (left.length && right.length) { left[ 0 ] <= right[ 0 ] ? result.push(left.shift()) : result.push(right.shift()); } while (left.length) result.push(left.shift()); while (right.length) result.push(right.shift()); return result; }