Skip to content

Commit f484ee4

Browse files
committed
Improved the JS implementation for Bubble Sort
1 parent 16147f5 commit f484ee4

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed

contents/bubble_sort/bubble_sort.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ This means that we need to go through the vector $$\mathcal{O}(n^2)$$ times with
1919
{% sample lang="kotlin" %}
2020
[import:1-11, lang:"kotlin"](code/kotlin/BubbleSort.kt)
2121
{% sample lang="js" %}
22-
[import:1-11, lang:"javascript"](code/javascript/bubble.js)
22+
[import:1-12, lang:"javascript"](code/javascript/bubble.js)
2323
{% sample lang="py" %}
2424
[import:4-9, lang:"python"](code/python/bubblesort.py)
2525
{% sample lang="m" %}

contents/bubble_sort/code/javascript/bubble.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
function bubbleSort(arr) {
2-
for (let r = arr.length -1; r > 0; r--) {
3-
for (let i = 0; i < r; i++) {
4-
if (arr[i] > arr[i + 1]) {
5-
let tmp = arr[i];
6-
arr[i] = arr[i + 1];
7-
arr[i + 1] = tmp;
2+
let tmp;
3+
for (let i = 0; i < arr.length; i++) {
4+
for (let k = 0; k < arr.length - 1; k++) {
5+
if (arr[k] > arr[k + 1]) {
6+
tmp = arr[k];
7+
arr[k] = arr[k + 1];
8+
arr[k + 1] = tmp;
89
}
910
}
1011
}
1112
}
1213

1314
function main() {
14-
const testArray = [4, 5, 123, 759, -132, 8940, 24, 34, -5];
15+
const testArray = [1, 3, 2, 4, 5, 10, 50, 7, 1.5, 0.3];
1516
bubbleSort(testArray);
1617
console.log(testArray);
1718
}

0 commit comments

Comments
 (0)