// Bubble Sort Algorithm
const bubbleSort = (arr) => {
let changePosition;
do {
changePosition = false;
arr.map((elm, i) => {
if (elm > arr[i+1]) {
arr[i] = arr[i+1];
arr[i+1] = elm;
changePosition = true;
}
})
} while (changePosition === true)
return arr;
}
console.log(bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]));
// Selection Sort Algorithm
const selectionSort = (arr) => {
let min = [], length = arr.length;
while (length--) {
min.push(Math.min(...arr));
arr[arr.indexOf(Math.min(...arr))] = arr[0];
arr.shift();
}
return min;
}
console.log(selectionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]));
// Insertion Sort Algorithm
const insertionSort = (arr) => {
arr.map((elm, i) => {
let val = arr[i];
while (i > 0 && arr[i - 1] > val) {
arr[i] = arr[i-1];
i--;
}
arr[i] = val;
})
return arr;
}
console.log(insertionSort([0, 0, 0, 0]));
// Marge Sort Algorithm
const mergeSort = (int) => {
const merge = (left, right) => {
let output = [];
while(left.length && right.length) {
output.push(left[0] < right[0] ? left.shift() : right.shift());
}
while(left.length) {
output.push(left.shift());
}
while(right.length) {
output.push(right.shift())
}
return output;
}
if (int.length < 2) {
return int;
}
const breakPoint = Math.round(int.length / 2);
return merge(mergeSort(int.slice(0, breakPoint)), mergeSort(int.slice(breakPoint)));
}
console.log(mergeSort([1,3,2,8, 6, 5, 7, 4]));
// Quick Sort Algorithm
function quickSort(arr) {
let left = [], right = [], breakPoint = arr.length - 1, x = [];
for (let i = 0; i < arr.length - 1; i++) {
arr[i] <= breakPoint ? left.push(arr[i]) : right.push(arr[i]);
}
return [...quickSort(left), breakPoint, ...quickSort(right)]
}
console.log(quickSort([1,3,2,4,6,5,8,9,7]));
Last active
July 28, 2018 09:06
-
-
Save Jobayer-Ahmed/f49151dd8c7bf87038dc17f7dfe34dac to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment