Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Implement sleep sort #1842

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
edlerd wants to merge 1 commit into TheAlgorithms:master
base: master
Choose a base branch
Loading
from edlerd:sleep-sort
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Sorts/SleepSort.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Implementation of the sleep sort algorithm.
*
* This sorting algorithm delays each input element by an amount of time
* proportional to its value before adding it to the result
*
* @see https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
*/
export function sleepSort(arr) {
return new Promise((resolve) => {
const result = []
let count = 0

arr.forEach((num) => {
// Use setTimeout proportional to the number
setTimeout(() => {
result.push(num)
count++
if (count === arr.length) {
resolve(result)
}
}, num)
})
})
}
8 changes: 8 additions & 0 deletions Sorts/test/SleepSort.test.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { sleepSort } from '../SleepSort.js'

describe('sleepSort', () => {
it('should sort the array', async () => {
const result = await sleepSort([5, 6, 7, 8, 1, 2, 12, 14])
expect(result).toEqual([1, 2, 5, 6, 7, 8, 12, 14])
})
})

AltStyle によって変換されたページ (->オリジナル) /