Skip to content

Commit 5d329b5

Browse files
Hui ChenHui Chen
authored andcommitted
Added cycle sort
1 parent e150866 commit 5d329b5

File tree

4 files changed

+76
-1
lines changed

4 files changed

+76
-1
lines changed

algorithm/category.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@
4141
"radix": "Radix Sort",
4242
"quick": "Quicksort",
4343
"heap" : "Heapsort",
44-
"shell": "Shellsort"
44+
"shell": "Shellsort",
45+
"cycle": "Cycle Sort"
4546
}
4647
},
4748
"string": {
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
logger._print( 'original array = [' + D.join(', ') + ']' );
2+
var N = D.length;
3+
var writes = 0;
4+
var pos;
5+
var item;
6+
var temp;
7+
for( cycleStart=0; cycleStart<=N-2; cycleStart++ ){
8+
item = D[cycleStart];
9+
pos = cycleStart;
10+
for( i=cycleStart+1; i<=N-1; i++ ){
11+
if( D[i]<item ){
12+
pos++;
13+
}
14+
}
15+
if( pos == cycleStart ){
16+
continue;
17+
}
18+
while( item == D[pos] ){
19+
pos++;
20+
}
21+
temp = D[pos];
22+
D[pos] = item;
23+
item = temp;
24+
25+
logger._print( 'Rewrite '+D[pos]+' to index '+pos );
26+
27+
tracer._notify(pos, D[pos])._notify(cycleStart, D[cycleStart])._wait();
28+
tracer._denotify(pos)._denotify(pos);
29+
30+
31+
while( pos != cycleStart ){
32+
pos = cycleStart;
33+
for( i=cycleStart+1; i<=N-1; i++ ){
34+
if( D[i]<item ){
35+
pos++;
36+
}
37+
}
38+
39+
while( item == D[pos] ){
40+
pos++;
41+
}
42+
temp = D[pos];
43+
D[pos] = item;
44+
item = temp;
45+
46+
logger._print( 'Rewrite '+D[pos]+' to index '+pos );
47+
48+
tracer._notify(pos, D[pos])._notify(cycleStart, D[cycleStart])._wait();
49+
tracer._denotify(pos)._denotify(pos);
50+
51+
writes++;
52+
}
53+
54+
writes++;
55+
}
56+
57+
logger._print( 'Number of writes performed is ' + writes );
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
var tracer = new Array1DTracer();
2+
var logger = new LogTracer();
3+
var D = Array1D.random(15);
4+
tracer._setData(D);

algorithm/sorting/cycle/desc.json

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"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.",
3+
"Complexity": {
4+
"time": "worst O(n<sup>2</sup>), best O(n<sup>2</sup>), average O(n<sup>2</sup>)",
5+
"space": "worst O(1) auxiliary"
6+
},
7+
"References": [
8+
"<a href='https://en.wikipedia.org/wiki/Cycle_sort'>Wikipedia</a>"
9+
],
10+
"files": {
11+
"basic": "Cycle Sort"
12+
}
13+
}

0 commit comments

Comments
 (0)