Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1824b4c

Browse files
committed
feat: 冒泡排序
1 parent e7b3cb7 commit 1824b4c

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

排序/冒泡排序.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,16 @@ function bubbleSort(arr) {
99

1010
for (let i = 0; i < n; i++) {
1111
let flag = false;
12+
// 从前往后冒泡 所以已经处理过的就不用再访问了
13+
// 并且由于每次遍历会访问j+1项,等于提前遍历了后一项
14+
// 所以这里的终止条件可以是n - i再减去1
1215
for (let j = 0; j < n - 1 - i; j++) {
1316
if (arr[j] > arr[j + 1]) {
1417
swap(arr, j, j + 1);
1518
flag = true;
1619
}
1720
}
21+
// 如果这次循环都没有数字被交换 说明已经是排序好的数组
1822
if (!flag) return arr;
1923
}
2024
return arr;

0 commit comments

Comments
 (0)