forked from algorithm-visualizer/algorithm-visualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
80 lines (66 loc) · 2.1 KB
/
code.js
File metadata and controls
80 lines (66 loc) · 2.1 KB
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
logger._print('original array = [' + D.join(', ') + ']');
var N = D.length;
var writes = 0; // number of writing performed
var pos; // the index of item in the sorted array
var item; // an item in the array
var temp; // a temp value used for storing swapped item
for (var cycleStart = 0; cycleStart <= N - 2; cycleStart++) {
item = D[cycleStart];
// find where to put the item
pos = cycleStart;
tracer._select(cycleStart);
for (var i = cycleStart + 1; i <= N - 1; i++) {
tracer._select(i)._wait()._deselect(i);
if (D[i] < item) {
pos++;
}
}
// if the item is already there, this is not a circle
if (pos === cycleStart) {
tracer._deselect(cycleStart);
continue;
}
// otherwise put the item there or right after any duplicates
while (item === D[pos]) {
pos++;
}
// write item to new index and increment writes
temp = D[pos];
D[pos] = item;
item = temp;
writes++;
if (pos !== cycleStart) {
logger._print('Rewrite ' + D[pos] + ' to index ' + pos + '; the next value to rewrite is ' + item);
} else {
logger._print('Rewrite ' + D[pos] + ' to index ' + pos);
}
tracer._select(pos)._wait()._deselect(pos);
tracer._notify(pos, D[pos])._notify(cycleStart, D[cycleStart])._wait();
tracer._denotify(pos)._denotify(cycleStart);
// rotate the rest of the cycle
while (pos !== cycleStart) {
pos = cycleStart;
for (i = cycleStart + 1; i <= N - 1; i++) {
tracer._select(i)._wait()._deselect(i);
if (D[i] < item) {
pos++;
}
}
while (item === D[pos]) {
pos++;
}
temp = D[pos];
D[pos] = item;
item = temp;
if (pos !== cycleStart) {
logger._print('Rewrite ' + D[pos] + ' to index ' + pos + '; the next value to rewrite is ' + item);
} else {
logger._print('Rewrite ' + D[pos] + ' to index ' + pos);
}
tracer._select(pos)._wait()._deselect(pos);
tracer._notify(pos, D[pos])._notify(cycleStart, D[cycleStart])._wait();
tracer._denotify(pos)._denotify(cycleStart);
writes++;
}
}
logger._print('Number of writes performed is ' + writes);