2

Given the following sorting algorithm, what is the time complexity of the sort?

function sort(arr) {
  arr.forEach(i => {
    setTimeout(() => console.log(i), i)
  })
}

const n = [100, 1000000, 10000, 3600000, 3, 5, 0, 1, 9];
sort(n);

Output:

0
1
3
5
9
100
10000
3600000 // After 1 hour
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chuma Umenze
  • 933
  • 12
  • 18
  • The solution appears to be `O(n)`. However, I am not convinced the `setTimeout` is insignificant. And I also think it's `O(n*nᵢ)`. – Chuma Umenze Aug 17 '20 at 22:48
  • That is a sorting algorithm? lol, I would not be surprised if that would produce invalid results since setTimeout is not really accurate. :) – epascarello Aug 17 '20 at 22:59
  • @epascarello the algorithm is impractical and unreliable. It's for academic purpose. – Chuma Umenze Aug 17 '20 at 23:11
  • If the question is "time complexity", that is, what drives the overall duration of the function, it's not the number of entries, which is typically denoted by "n" in big-O notation, but rather, it's the max entry. Eg, sorting [ 10,9,8,7,6,5,4,3,2,1 ] where n = 10 will still be ~10x quicker than sorting [ 100 ] where n = 1. So, I should think the time complexity is directly proportional to the maximum value being sorted, and thus O( max( x) ). – Trentium Aug 18 '20 at 20:35
  • Actually, the imprecision of setTimeout as nothing to do here, the order must be preserved, so as long as the function's call spans on the same wall clock's ms it's quite reliable. The issue that could arise is if multiple values have less than n-ms of differences and the call to setTimeout for the higher value is done before, e.g `setTimeout( ()=>console.log(2), 2 ); /*....a few ms later because it's a big input */ setTimeout( ()=>console.log(1), 1 );`. Here you'd have 2 logged before 1, because the timeout is relative to call time. – Kaiido Oct 29 '20 at 05:57

0 Answers0