Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9f7639e

Browse files
authored
Merge pull request #74 from KuLi/cycleSort
Implemented cycle sort algorithm
2 parents 2d50357 + 7a81493 commit 9f7639e

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

‎Sorts/cycleSort.js‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
Wikipedia says: Cycle sort is an in-place, unstable sorting algorithm,
3+
a comparison sort that is theoretically optimal in terms of the total
4+
number of writes to the original array, unlike any other in-place sorting
5+
algorithm. It is based on the idea that the permutation to be sorted can
6+
be factored into cycles, which can individually be rotated to give a sorted result.
7+
*/
8+
function cycleSort(list) {
9+
10+
let writes = 0;
11+
for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
12+
13+
let value = list[cycleStart];
14+
let position = cycleStart;
15+
16+
// search position
17+
for (let i = cycleStart+1; i < list.length; i++) {
18+
19+
if (list[i] < value) {
20+
position++;
21+
}
22+
}
23+
// if its the same continue
24+
if (position == cycleStart) {
25+
continue;
26+
}
27+
28+
while (value == list[position]) {
29+
position++;
30+
}
31+
32+
let oldValue = list[position];
33+
list[position] = value;
34+
value = oldValue;
35+
writes++;
36+
37+
// rotate the rest
38+
while (position != cycleStart) {
39+
position = cycleStart;
40+
for (let i = cycleStart +1; i < list.length; i++) {
41+
42+
if (list[i] < value) {
43+
position++;
44+
}
45+
}
46+
while (value == list[position]) {
47+
position++;
48+
}
49+
let oldValueCycle = list[position];
50+
list[position] = value;
51+
value = oldValueCycle;
52+
writes++;
53+
}
54+
}
55+
return writes;
56+
}
57+
let arrOrignal = [5, 6, 7, 8, 1, 2,12, 14];
58+
//Array before Sort
59+
console.log(arrOrignal);
60+
cycleSort(arrOrignal);
61+
//Array after sort
62+
console.log(arrOrignal);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /