LearnFrenzy
Sign in Take a free test

Event Loop · Event Loop Coding Problems · Question 5

Sleep sort with setTimeout in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Implement the (joke) "sleep sort": schedule each number with a delay proportional to its value and collect them as the timers fire. Explain why it is not a real sorting algorithm.

Solution
main.js
function sleepSort(nums, done) {
  const sorted = [];
  nums.forEach((n) => {
    setTimeout(() => {
      sorted.push(n);
      if (sorted.length === nums.length) done(sorted);
    }, n * 10);
  });
}

sleepSort([5, 2, 8, 1, 4], (sorted) => console.log("sorted:", sorted.join(" ")));

Output Verified by running it on Node.js

sorted: 1 2 4 5 8

The timer queue does the sorting, by due time. It only works for small non-negative numbers spaced far enough apart, and its running time depends on the largest value – a fun way to show that timers fire in due-time order.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links