mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
60 lines
1.6 KiB
JavaScript
60 lines
1.6 KiB
JavaScript
/**
|
|
* Cycle sort is an in-place, unstable sorting algorithm,
|
|
* a comparison sort that is theoretically optimal in terms of the total
|
|
* number of writes to the original array, unlike any other in-place sorting
|
|
* algorithm. It is based on the idea that the permutation to be sorted can
|
|
* be factored into cycles, which can individually be rotated to give a sorted result.
|
|
*
|
|
* Wikipedia: https://en.wikipedia.org/wiki/Cycle_sort
|
|
*/
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
function cycleSort(list) {
|
|
for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
|
|
let value = list[cycleStart]
|
|
let position = cycleStart
|
|
|
|
// search position
|
|
for (let i = cycleStart + 1; i < list.length; i++) {
|
|
if (list[i] < value) {
|
|
position++
|
|
}
|
|
}
|
|
// if it is the same, continue
|
|
if (position === cycleStart) {
|
|
continue
|
|
}
|
|
while (value === list[position]) {
|
|
position++
|
|
}
|
|
|
|
const oldValue = list[position]
|
|
list[position] = value
|
|
value = oldValue
|
|
|
|
// rotate the rest
|
|
while (position !== cycleStart) {
|
|
position = cycleStart
|
|
for (let i = cycleStart + 1; i < list.length; i++) {
|
|
if (list[i] < value) {
|
|
position++
|
|
}
|
|
}
|
|
while (value === list[position]) {
|
|
position++
|
|
}
|
|
const oldValueCycle = list[position]
|
|
list[position] = value
|
|
value = oldValueCycle
|
|
}
|
|
}
|
|
return list
|
|
}
|
|
|
|
export { cycleSort }
|