This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
} |