MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / cycleSort

Function cycleSort

Sorts/CycleSort.js:17–57  ·  view source on GitHub ↗

* cycleSort takes an input array of numbers and returns the array sorted in increasing order. * * @param {number[]} list An array of numbers to be sorted. * @return {number[]} An array of numbers sorted in increasing order.

(list)

Source from the content-addressed store, hash-verified

15 * @return {number[]} An array of numbers sorted in increasing order.
16 */
17function cycleSort(list) {
18 for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
19 let value = list[cycleStart]
20 let position = cycleStart
21
22 // search position
23 for (let i = cycleStart + 1; i < list.length; i++) {
24 if (list[i] < value) {
25 position++
26 }
27 }
28 // if it is the same, continue
29 if (position === cycleStart) {
30 continue
31 }
32 while (value === list[position]) {
33 position++
34 }
35
36 const oldValue = list[position]
37 list[position] = value
38 value = oldValue
39
40 // rotate the rest
41 while (position !== cycleStart) {
42 position = cycleStart
43 for (let i = cycleStart + 1; i < list.length; i++) {
44 if (list[i] < value) {
45 position++
46 }
47 }
48 while (value === list[position]) {
49 position++
50 }
51 const oldValueCycle = list[position]
52 list[position] = value
53 value = oldValueCycle
54 }
55 }
56 return list
57}
58
59export { cycleSort }

Callers 1

CycleSort.test.jsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected