From 5c30fac74f39120a96267e548b90cbe0cac7b80e Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 27 Dec 2020 21:20:31 +0200 Subject: [PATCH] Add bubble sort --- snippets/bubbleSort.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 snippets/bubbleSort.md diff --git a/snippets/bubbleSort.md b/snippets/bubbleSort.md new file mode 100644 index 000000000..8e0396284 --- /dev/null +++ b/snippets/bubbleSort.md @@ -0,0 +1,41 @@ +--- +title: bubbleSort +tags: algorithm,array,beginner +--- + +Sorts an array of numbers, using the bubble sort algorithm. + +- Declare a variable, `swapped`, that indicates if any values were swapped during the current iteration. +- Use the spread operator (`...`) to clone the original array, `arr`. +- Use a `for` loop to iterate over the elements of the cloned array, terminating before the last element. +- Use a nested `for` loop to iterate over the segment of the array between `0` and `i`, swapping any adjacent out of order elements and setting `swapped` to `true`. +- If `swapped` is `false` after an iteration, no more changes are needed, so the cloned array is returned. + +```js +const bubbleSort = arr => { + let swapped = false; + + const a = [...arr]; + + for (let i = 1; i < a.length - 1; i++) { + swapped = false; + + for (let j = 0; j < a.length - i; j++) { + if (a[j + 1] < a[j]) { + [a[j], a[j + 1]] = [a[j + 1], a[j]]; + swapped = true; + } + } + + if (!swapped) { + return a; + } + } + + return a; +}; +``` + +```js +bubbleSort([2, 1, 4, 3]); // [1, 2, 3, 4] +```