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>
39 lines
811 B
JavaScript
39 lines
811 B
JavaScript
/**
|
|
* Checks whether the given array is sorted in ascending order.
|
|
*/
|
|
export function isSorted(array) {
|
|
const length = array.length
|
|
for (let i = 0; i < length - 1; i++) {
|
|
if (array[i] > array[i + 1]) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
/**
|
|
* Shuffles the given array randomly in place.
|
|
*/
|
|
function shuffle(array) {
|
|
for (let i = array.length - 1; i; i--) {
|
|
const m = Math.floor(Math.random() * i)
|
|
const n = array[i - 1]
|
|
array[i - 1] = array[m]
|
|
array[m] = n
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Implementation of the bogosort algorithm.
|
|
*
|
|
* This sorting algorithm randomly rearranges the array until it is sorted.
|
|
*
|
|
* For more information see: https://en.wikipedia.org/wiki/Bogosort
|
|
*/
|
|
export function bogoSort(items) {
|
|
while (!isSorted(items)) {
|
|
shuffle(items)
|
|
}
|
|
return items
|
|
}
|