sorting algorithms in javascript

Sorting Algorithms in Javascript

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

Bubble Sort:

``````
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;
};
``````

Insertion Sort:

``````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;
}
``````

Selection Sort:

``````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;
}
``````

Merge Sort:

``````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;
}
``````

Quick Sort:

``````let quicksort = function(arr) {
if(arr.length <= 1) return arr;

let pivot = Math.floor((arr.length -1)/2);
let val = arr[pivot], less = [], more = [];

arr.splice(pivot, 1);
arr.forEach(function(e,i,a){
e < val ? less.push(e) : more.push(e);
});

return (quicksort(less)).concat([val],quicksort(more))
}
``````