* 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)
| 15 | * @return {number[]} An array of numbers sorted in increasing order. |
| 16 | */ |
| 17 | function 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 | |
| 59 | export { cycleSort } |