-
Notifications
You must be signed in to change notification settings - Fork 1
/
bubble.ts
83 lines (71 loc) · 1.73 KB
/
bubble.ts
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
function* bubble(a: number[]): StepGenerator {
let accesses = 0
let comparisons = 0
for (let n = a.length; n > 1; /* empty */) {
accesses++
let m = 0
for (let i = 1; i < n; i++) {
accesses++, comparisons++
yield [accesses, comparisons, [i-1, i]]
accesses++
if (a[i-1] > a[i]) {
a.swap(i-1, i)
m = i
}
}
accesses++
n = m
}
return [accesses, comparisons] as Pair<number>
}
/*
n ← a.length
while n > 1
x ← a[0]
m ← 0
for i in 1 until n
y ← a[i]
if x > y
a[i-1] ← y
m ← i
else
a[i-1] ← x
x ← y
a[n-1] ← x
n ← m
*/
function* bubbleBi(a: number[]): StepGenerator {
let accesses = 0
let comparisons = 0
// inclusive
let iStart = 0
let iEnd = a.length-1
while (iStart < iEnd /* i.e. there are >=2 unsorted elements */) {
let iNew = iStart
accesses++
for (let i = iStart+1; i <= iEnd; i++) {
accesses++, comparisons++
yield [accesses, comparisons, [i-1, i]]
accesses++
if (a[i-1] > a[i]) {
a.swap(i-1, i)
iNew = i
}
}
accesses++
iEnd = --iNew
accesses++
for (let i = iEnd; i > iStart; i--) {
accesses++, comparisons++
yield [accesses, comparisons, [i-1, i]]
accesses++
if (a[i-1] > a[i]) {
a.swap(i-1, i)
iNew = i
}
}
accesses++
iStart = iNew
}
return [accesses, comparisons] as Pair<number>
}