Skip to content

Commit 9eede37

Browse files
Merge pull request akshitagit#166 from Subhransu02/big
cycle_sort in js added
2 parents a9150ca + e2f54cd commit 9eede37

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Algorithms/cyclic_sort.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
function cycleSort(array) {
2+
// loop from the beginning of the array to the second to last item
3+
for (let currentIndex = 0; currentIndex < array.length - 1; currentIndex++) {
4+
// save the value of the item at the currentIndex
5+
let item = array[currentIndex]
6+
7+
let currentIndexCopy = currentIndex
8+
// loop through all indexes that proceed the currentIndex
9+
for (let i = currentIndex + 1; i < array.length; i++)
10+
if (array[i] < item)
11+
currentIndexCopy++
12+
13+
// if currentIndexCopy has not changed, the item at the currentIndex is already in the correct currentIndexCopy
14+
if (currentIndexCopy == currentIndex)
15+
continue
16+
17+
// skip duplicates
18+
while (item == array[currentIndexCopy])
19+
currentIndexCopy++
20+
21+
// swap
22+
let temp = array[currentIndexCopy]
23+
array[currentIndexCopy] = item
24+
item = temp
25+
26+
// repeat above steps as long as we can find values to swap
27+
while (currentIndexCopy != currentIndex) {
28+
currentIndexCopy = currentIndex
29+
// loop through all indexes that proceed the currentIndex
30+
for (let i = currentIndex + 1; i < array.length; i++)
31+
if (array[i] < item)
32+
currentIndexCopy++
33+
34+
// skip duplicates
35+
while (item == array[currentIndexCopy])
36+
currentIndexCopy++
37+
38+
// swap
39+
temp = array[currentIndexCopy]
40+
array[currentIndexCopy] = item
41+
item = temp
42+
}
43+
}
44+
}
45+
46+
let array = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8]
47+
cycleSort(array)
48+
alert(array)

0 commit comments

Comments
 (0)