Skip to content

Instantly share code, notes, and snippets.

@RaphGL
Last active September 20, 2023 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaphGL/fa4299978b8e584824a75636b891d4d5 to your computer and use it in GitHub Desktop.
Save RaphGL/fa4299978b8e584824a75636b891d4d5 to your computer and use it in GitHub Desktop.
Sorting Algorithms in JavaScript
function bubbleSort(myArr) {
for (let j = myArr.length - 1; j > 0; j--) {
let biggest = myArr[j];
for (let i = 0; i < j; i++) {
const item1 = myArr[i];
const item2 = myArr[i + 1];
if (item1 > item2) {
myArr[i] = item2;
myArr[i + 1] = item1;
}
if (item1 > biggest) biggest = item1;
}
myArr[j] = biggest;
}
}
function selectionSort(myArr) {
for (let i = 0; i < myArr.length; i++) {
let min = myArr[i];
let minIdx = i;
for (let j = i; j < myArr.length; j++) {
if (myArr[j] < min) {
min = myArr[j];
minIdx = j;
}
}
const tmp = myArr[i];
myArr[i] = min;
myArr[minIdx] = tmp;
}
}
function insertionSort(myArr) {
for (let i = 1; i < myArr.length; i++) {
let key = myArr[i];
let j = i - 1;
while (key < myArr[j] && j >= 0) {
myArr[j + 1] = myArr[j];
--j;
}
myArr[j + 1] = key;
}
}
function measureExecutionSpeed(sortingFunc) {
let myArr = [1, 2, 9, 4, 9, 7, 3, 30, 21, 5];
let start = performance.now();
sortingFunc(myArr);
let end = performance.now();
function functionName(func) {
let name = func.toString();
name = name.substr("function ".length);
name = name.substr(0, name.indexOf("("));
return name;
}
function checkSorted(myArr) {
for (let i = 0; i < myArr.length - 1; i++) {
if (myArr[i] > myArr[i + 1]) {
console.log("Array was not sorted.");
return;
}
}
console.log("Array was sorted");
}
console.log(functionName(sortingFunc), end - start);
checkSorted(myArr);
}
const algorithms = [bubbleSort, selectionSort, insertionSort];
algorithms.forEach(measureExecutionSpeed);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment