Skip to content

Instantly share code, notes, and snippets.

@bullgare bullgare/sorting.js
Created Mar 1, 2018

Embed
What would you like to do?
bubble, selection, merge, and quick sorts
function bubbleSort(arr) {
for (let outer = 0; outer < arr.length; outer++) {
for (let i = 0; i < arr.length - 1 - outer; i++) {
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
}
}
}
return arr;
}
function selectionSort(arr) {
for (let outer = 0; outer < arr.length; outer++) {
let min = arr[outer], pos = outer;
for (let i = outer + 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
pos = i;
}
}
[arr[outer], arr[pos]] = [arr[pos], arr[outer]];
}
return arr;
}
function mergeSort(arr) {
if (arr.length === 1) {
return arr;
}
const mid = Math.floor(arr.length / 2);
return merge(mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid)));
}
function merge(left, right) {
const arr = [];
while (left.length || right.length) {
if (!right.length || (left.length && left[0] < right[0])) {
arr.push(left.shift());
} else {
arr.push(right.shift());
}
}
return arr;
}
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
const referencePoint = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
let item = arr[i];
if (item < referencePoint) {
left.push(item);
} else {
right.push(item);
}
}
return [...quickSort(left), referencePoint, ...quickSort(right)];
}
module.exports = { bubbleSort, selectionSort, mergeSort, quickSort };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.