Skip to content

Commit 4e00b4e

Browse files
Hui ChenHui Chen
authored andcommitted
added comments in code.js
1 parent 8ff1039 commit 4e00b4e

File tree

1 file changed

+14
-6
lines changed
  • algorithm/sorting/cycle/basic

1 file changed

+14
-6
lines changed

algorithm/sorting/cycle/basic/code.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
logger._print('original array = [' + D.join(', ') + ']');
22
var N = D.length;
3-
var writes = 0;
4-
var pos;
5-
var item;
6-
var temp;
3+
var writes = 0; // number of writing performed
4+
var pos; // the index of item in the sorted array
5+
var item; // an item in the array
6+
var temp; // a temp value used for storing swapped item
77
for (var cycleStart = 0; cycleStart <= N - 2; cycleStart++) {
88
item = D[cycleStart];
9+
10+
// find where to put the item
911
pos = cycleStart;
1012
tracer._select(cycleStart);
1113

@@ -15,18 +17,25 @@ for (var cycleStart = 0; cycleStart <= N - 2; cycleStart++) {
1517
pos++;
1618
}
1719
}
20+
21+
// if the item is already there, this is not a circle
1822
if (pos == cycleStart) {
1923
tracer._deselect(cycleStart);
2024
continue;
2125
}
26+
27+
// otherwise put the item there or right after any duplicates
2228
while (item == D[pos]) {
2329
pos++;
2430
}
2531

32+
// write item to new index and increment writes
2633
temp = D[pos];
2734
D[pos] = item;
2835
item = temp;
2936

37+
writes++;
38+
3039
if (pos !== cycleStart) {
3140
logger._print('Rewrite ' + D[pos] + ' to index ' + pos + '; the next value to rewrite is ' + item);
3241
} else {
@@ -36,6 +45,7 @@ for (var cycleStart = 0; cycleStart <= N - 2; cycleStart++) {
3645
tracer._notify(pos, D[pos])._notify(cycleStart, D[cycleStart])._wait();
3746
tracer._denotify(pos)._denotify(cycleStart);
3847

48+
// rotate the rest of the cycle
3949
while (pos != cycleStart) {
4050
pos = cycleStart;
4151

@@ -65,8 +75,6 @@ for (var cycleStart = 0; cycleStart <= N - 2; cycleStart++) {
6575

6676
writes++;
6777
}
68-
69-
writes++;
7078
}
7179

7280
logger._print('Number of writes performed is ' + writes);

0 commit comments

Comments
 (0)