Skip to content

Instantly share code, notes, and snippets.

View jayantasamaddar's full-sized avatar
🕵️
Looking for interesting problems to solve

Jayanta Samaddar jayantasamaddar

🕵️
Looking for interesting problems to solve
View GitHub Profile
@jayantasamaddar
jayantasamaddar / insertionSort.js
Created May 23, 2022 21:02
Implement an Insertion Sort Algorithm
View insertionSort.js
/* Using C-Style for-loop */
const insertionSort = array => {
const arr = array.slice();
for (let i = 1; i < arr.length; i++) {
const sortedArr = arr.slice(0, i);
for (let j = 0; j < sortedArr.length; j++) {
if (sortedArr[j] > arr[i]) {
const pickedEl = arr.splice(i, 1)[0];
arr.splice(j, 0, pickedEl);
break;
@jayantasamaddar
jayantasamaddar / selectionSort.js
Created May 23, 2022 20:43
Implement a Selection Sort Algorithm
View selectionSort.js
/* Method 1 - Using C Style for-loop */
const selectionSort = array => {
const arr = array.slice();
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i; j < arr.length - 1; j++) {
const select = Math.min(...arr.slice(j, arr.length));
if (select < arr[j]) swap(arr, j, arr.lastIndexOf(select));
}
}
return arr;
@jayantasamaddar
jayantasamaddar / bubbleSort.js
Created May 23, 2022 13:25
Implement a Bubble Sort Algorithm
View bubbleSort.js
/* Using C Style for-Loop */
const bubbleSort = array => {
const arr = array.slice();
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
@jayantasamaddar
jayantasamaddar / swap.js
Created May 23, 2022 13:22
Swap two elements in an array located at different indexes
View swap.js
/* Swap - Using ES6 Array Destructuring */
const swap = (arr, indx1, indx2) => [arr[indx1], arr[indx2]] = [arr[indx2], arr[indx1]];
/* Swap - Pre-ES6 Version, using a temporary variable */
const swap2 = (arr, indx1, indx2) => {
const temp = arr[indx1];
arr[indx1] = arr[indx2];
arr[indx2] = temp;
}