Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion algorithm/category.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"radix": "Radix Sort",
"quick": "Quicksort",
"heap" : "Heapsort",
"shell": "Shellsort"
"shell": "Shellsort",
"cycle": "Cycle Sort"
}
},
"string": {
Expand Down
57 changes: 57 additions & 0 deletions algorithm/sorting/cycle/basic/code.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
logger._print( 'original array = [' + D.join(', ') + ']' );
var N = D.length;
var writes = 0;
var pos;
var item;
var temp;
for( cycleStart=0; cycleStart<=N-2; cycleStart++ ){
item = D[cycleStart];
pos = cycleStart;
for( i=cycleStart+1; i<=N-1; i++ ){
if( D[i]<item ){
pos++;
}
}
if( pos == cycleStart ){
continue;
}
while( item == D[pos] ){
pos++;
}
temp = D[pos];
D[pos] = item;
item = temp;

logger._print( 'Rewrite '+D[pos]+' to index '+pos );

tracer._notify(pos, D[pos])._notify(cycleStart, D[cycleStart])._wait();
tracer._denotify(pos)._denotify(pos);


while( pos != cycleStart ){
pos = cycleStart;
for( i=cycleStart+1; i<=N-1; i++ ){
if( D[i]<item ){
pos++;
}
}

while( item == D[pos] ){
pos++;
}
temp = D[pos];
D[pos] = item;
item = temp;

logger._print( 'Rewrite '+D[pos]+' to index '+pos );

tracer._notify(pos, D[pos])._notify(cycleStart, D[cycleStart])._wait();
tracer._denotify(pos)._denotify(pos);

writes++;
}

writes++;
}

logger._print( 'Number of writes performed is ' + writes );
4 changes: 4 additions & 0 deletions algorithm/sorting/cycle/basic/data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
var tracer = new Array1DTracer();
var logger = new LogTracer();
var D = Array1D.random(15);
tracer._setData(D);
13 changes: 13 additions & 0 deletions algorithm/sorting/cycle/desc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"Cycle Sort": "Cycle sort is an in-place, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array, unlike any other in-place sorting algorithm. It is based on the idea that the permutation to be sorted can be factored into cycles, which can individually be rotated to give a sorted result.",
"Complexity": {
"time": "worst O(n<sup>2</sup>), best O(n<sup>2</sup>), average O(n<sup>2</sup>)",
"space": "worst O(1) auxiliary"
},
"References": [
"<a href='https://en.wikipedia.org/wiki/Cycle_sort'>Wikipedia</a>"
],
"files": {
"basic": "Cycle Sort"
}
}