From 91f31f7a22f48bc6de9c6674f3a80cf83c7cbed2 Mon Sep 17 00:00:00 2001 From: Praneel-Shivarkar Date: Thu, 30 Oct 2025 20:31:59 +0530 Subject: [PATCH] feat: add --- Algorithms/sorting/bubblesort.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Algorithms/sorting/bubblesort.js diff --git a/Algorithms/sorting/bubblesort.js b/Algorithms/sorting/bubblesort.js new file mode 100644 index 0000000..c6920f0 --- /dev/null +++ b/Algorithms/sorting/bubblesort.js @@ -0,0 +1,18 @@ +// Ascending bubble sort with early exit +function bubbleSort(arr) { + const a = arr.slice(); // keep input unchanged [web:53] + for (let i = 0; i < a.length - 1; i++) { + let swapped = false; // optimization flag [web:53] + for (let j = 0; j < a.length - i - 1; j++) { + if (a[j] > a[j + 1]) { // compare adjacent [web:66] + [a[j], a[j + 1]] = [a[j + 1], a[j]]; // swap [web:53] + swapped = true; + } + } + if (!swapped) break; // already sorted → stop [web:53] + } + return a; +} + +// Example +console.log(bubbleSort([5, 1, 4, 2, 8])); // [1, 2, 4, 5, 8] [web:53]