From e693c0078c7a7a8aaf917108a52bc940712e4af8 Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:51:58 +1000 Subject: [PATCH] Algorithms: Implement Bubble Sort --- Algorithms/bubbleSort.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Algorithms/bubbleSort.js diff --git a/Algorithms/bubbleSort.js b/Algorithms/bubbleSort.js new file mode 100644 index 0000000..f603d9c --- /dev/null +++ b/Algorithms/bubbleSort.js @@ -0,0 +1,22 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-bubble-sort + +function bubbleSort(array) { + // Only change code below this line + function swap(array, indexA, indexB) { + const tmp = array[indexA]; + array[indexA] = array[indexB]; + array[indexB] = tmp; + } + let swaps = false; + do { + swaps = false; + for (let i = 0; i < array.length - 1; i++) { + if (array[i] > array[i + 1]) { + swaps = true; + swap(array, i, i + 1); + } + } + } while (swaps); + return array; + // Only change code above this line +}