Skip to content
Prev Previous commit
Next Next commit
Avoid mutating input array in bubble sort implementations
  • Loading branch information
MayankSharma-2812 committed Jan 26, 2026
commit ddf6fb23ba939ebb8bfd36abe18a1c481ac40282
40 changes: 23 additions & 17 deletions Sorts/BubbleSort.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,30 @@
/* Bubble Sort is an algorithm to sort an array. It
* compares adjacent element and swaps their position
* The big O on bubble sort in worst and best case is O(N^2).
* Not efficient.
* Somehow if the array is sorted or nearly sorted then we can optimize bubble sort by adding a flag.
* compares adjacent elements and swaps their position.
* The big O on bubble sort in worst and best case is O(N^2).
*
* In bubble sort, we keep iterating while something was swapped in
* the previous inner-loop iteration. By swapped I mean, in the
* inner loop iteration, we check each number if the number proceeding
* it is greater than itself, if so we swap them.
*
* Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
* Animated Visual: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
* Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
*/

/**
* Using 2 for loops.
*/
export function bubbleSort(items) {
export function bubbleSort(list) {
if (!Array.isArray(list)) {
throw new TypeError('Given input is not an array')
}

if (list.length === 0) {
return []
}

const items = [...list]
const length = items.length
let noSwaps

for (let i = length; i > 0; i--) {
// flag for optimization
noSwaps = true
// Number of passes
for (let j = 0; j < i - 1; j++) {
// Compare the adjacent positions
if (items[j] > items[j + 1]) {
// Swap the numbers
;[items[j], items[j + 1]] = [items[j + 1], items[j]]
noSwaps = false
}
Expand All @@ -43,7 +40,16 @@ export function bubbleSort(items) {
/**
* Using a while loop and a for loop.
*/
export function alternativeBubbleSort(arr) {
export function alternativeBubbleSort(list) {
if (!Array.isArray(list)) {
throw new TypeError('Given input is not an array')
}

if (list.length === 0) {
return []
}

const arr = [...list]
let swapped = true

while (swapped) {
Expand Down