Skip to content

Commit 03e8929

Browse files
committed
Optimizzed bubbleSort with noSwaps
1 parent 116d614 commit 03e8929

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

11-bubble-sort/bubbleSort.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,31 @@
1111
// return arr;
1212
// };
1313

14+
// const bubbleSort = (arr) => {
15+
// for (let i = arr.length; i > 0; i--) {
16+
// for (let j = 0; j < i - 1; j++) {
17+
// if (arr[j] > arr[j + 1]) {
18+
// [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
19+
// }
20+
// }
21+
// }
22+
23+
// return arr;
24+
// };
25+
26+
// Optimized with noSwaps
1427
const bubbleSort = (arr) => {
28+
let noSwaps;
29+
1530
for (let i = arr.length; i > 0; i--) {
31+
noSwaps = true;
1632
for (let j = 0; j < i - 1; j++) {
1733
if (arr[j] > arr[j + 1]) {
1834
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
35+
noSwaps = false;
1936
}
2037
}
38+
if (noSwaps) break;
2139
}
2240

2341
return arr;

0 commit comments

Comments
 (0)