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 +}