Skip to content

Commit 116d614

Browse files
committed
Add bubble sort
1 parent e449dcc commit 116d614

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

11-bubble-sort/bubbleSort.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Naive solution
2+
// const bubbleSort = (arr) => {
3+
// for (let i = 0; i < arr.length; i++) {
4+
// for (let j = 0; j < arr.length; j++) {
5+
// if (arr[j] > arr[j + 1]) {
6+
// [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
7+
// }
8+
// }
9+
// }
10+
11+
// return arr;
12+
// };
13+
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+
console.log(bubbleSort([1, 35, 2, 23, 3]));

0 commit comments

Comments
 (0)