# ❓ 冒泡排序如何实现,时间复杂度是多少, 还可以如何改进?
let arr = [
12,
34,
345,
634,
1,
324,
3543,
5345,
3,
5,
453,
5,
353,
5,
45,
345,
34,
534,
-12,
23,
213,
]
// 时间复杂度 O(n^2)
function bubble(target) {
for (let x = 0; x < target.length; x++)
for (let y = x + 1; y < target.length; y++)
if (target[x] > target[y]) [target[x], target[y]] = [target[y], target[x]]
return target
}
console.log(bubble(arr))
function bubble2(target) {
let x = 0
while (x < target.length) {
for (let y = x + 1; y < target.length; y++)
if (target[x] > target[y]) [target[x], target[y]] = [target[y], target[x]]
x++
}
return target
}
console.log(bubble2(arr))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48