From 1cddb2517b80c7c46c0c09b70f43d610b5783f5c Mon Sep 17 00:00:00 2001 From: Paulson J Paul Date: Wed, 20 Jan 2021 19:59:25 +0530 Subject: [PATCH] Add bubble sort JavaScript version --- sorting/README.md | 3 +++ sorting/js/bubble-sort.js | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 sorting/js/bubble-sort.js diff --git a/sorting/README.md b/sorting/README.md index 5cfb9dfe..d9d229ba 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -10,4 +10,7 @@ 1. [Bubble Sort](python/bubble-sort.py) +### JavaScript + +1. [Bubble Sort](js/bubble-sort.js) diff --git a/sorting/js/bubble-sort.js b/sorting/js/bubble-sort.js new file mode 100644 index 00000000..88c7661b --- /dev/null +++ b/sorting/js/bubble-sort.js @@ -0,0 +1,20 @@ +// Bubble Sorting JavaScript Version + +function bubbleSort(arr) { + // Copy the contents of the input array and store them as a separate variable + let sorted = [...arr]; + + // Loop through the copied array + for (let i = 0; i < sorted.length; i++) { + // Checks if an item in the array is greater than the item next to it (index + 1) + if (sorted[i] > sorted[i + 1]) { + // If yes, swap them + sorted.splice(i, 2, sorted[i + 1], sorted[i]); + } + } + // Finally return the sorted array + return sorted; +} + +// Log to the console and have fun +console.log(bubbleSort([23, 34, 25, 12, 54, 11]));