forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcyclic_sort.js
More file actions
48 lines (40 loc) · 1.55 KB
/
cyclic_sort.js
File metadata and controls
48 lines (40 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function cycleSort(array) {
// loop from the beginning of the array to the second to last item
for (let currentIndex = 0; currentIndex < array.length - 1; currentIndex++) {
// save the value of the item at the currentIndex
let item = array[currentIndex]
let currentIndexCopy = currentIndex
// loop through all indexes that proceed the currentIndex
for (let i = currentIndex + 1; i < array.length; i++)
if (array[i] < item)
currentIndexCopy++
// if currentIndexCopy has not changed, the item at the currentIndex is already in the correct currentIndexCopy
if (currentIndexCopy == currentIndex)
continue
// skip duplicates
while (item == array[currentIndexCopy])
currentIndexCopy++
// swap
let temp = array[currentIndexCopy]
array[currentIndexCopy] = item
item = temp
// repeat above steps as long as we can find values to swap
while (currentIndexCopy != currentIndex) {
currentIndexCopy = currentIndex
// loop through all indexes that proceed the currentIndex
for (let i = currentIndex + 1; i < array.length; i++)
if (array[i] < item)
currentIndexCopy++
// skip duplicates
while (item == array[currentIndexCopy])
currentIndexCopy++
// swap
temp = array[currentIndexCopy]
array[currentIndexCopy] = item
item = temp
}
}
}
let array = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8]
cycleSort(array)
alert(array)