Skip to content

Commit ddf6fb2

Browse files
Avoid mutating input array in bubble sort implementations
1 parent b135a51 commit ddf6fb2

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

Sorts/BubbleSort.js

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,30 @@
11
/* Bubble Sort is an algorithm to sort an array. It
2-
* compares adjacent element and swaps their position
3-
* The big O on bubble sort in worst and best case is O(N^2).
4-
* Not efficient.
5-
* Somehow if the array is sorted or nearly sorted then we can optimize bubble sort by adding a flag.
2+
* compares adjacent elements and swaps their position.
3+
* The big O on bubble sort in worst and best case is O(N^2).
64
*
7-
* In bubble sort, we keep iterating while something was swapped in
8-
* the previous inner-loop iteration. By swapped I mean, in the
9-
* inner loop iteration, we check each number if the number proceeding
10-
* it is greater than itself, if so we swap them.
11-
*
12-
* Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
13-
* Animated Visual: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
5+
* Wikipedia: https://en.wikipedia.org/wiki/Bubble_sort
146
*/
157

168
/**
179
* Using 2 for loops.
1810
*/
19-
export function bubbleSort(items) {
11+
export function bubbleSort(list) {
12+
if (!Array.isArray(list)) {
13+
throw new TypeError('Given input is not an array')
14+
}
15+
16+
if (list.length === 0) {
17+
return []
18+
}
19+
20+
const items = [...list]
2021
const length = items.length
2122
let noSwaps
2223

2324
for (let i = length; i > 0; i--) {
24-
// flag for optimization
2525
noSwaps = true
26-
// Number of passes
2726
for (let j = 0; j < i - 1; j++) {
28-
// Compare the adjacent positions
2927
if (items[j] > items[j + 1]) {
30-
// Swap the numbers
3128
;[items[j], items[j + 1]] = [items[j + 1], items[j]]
3229
noSwaps = false
3330
}
@@ -43,7 +40,16 @@ export function bubbleSort(items) {
4340
/**
4441
* Using a while loop and a for loop.
4542
*/
46-
export function alternativeBubbleSort(arr) {
43+
export function alternativeBubbleSort(list) {
44+
if (!Array.isArray(list)) {
45+
throw new TypeError('Given input is not an array')
46+
}
47+
48+
if (list.length === 0) {
49+
return []
50+
}
51+
52+
const arr = [...list]
4753
let swapped = true
4854

4955
while (swapped) {

0 commit comments

Comments
 (0)