PacktPublishing / Learning-JavaScript-Data-Structures-and-Algorithms-Third-Edition

Learning JavaScript Data Structures and Algorithms (Third Edition), published by Packt
MIT License
1.05k stars 428 forks source link

Calculation of the number of elements in bucket sorting #11

Closed PachVerb closed 3 years ago

PachVerb commented 3 years ago

Hello, I am learning bucket sorting. I don't understand the logic of a piece of code very well; or it is about the principle of calculating the number of elements in the bucket sorting bucket. code show as below:

....
const buketCount: number =
    Math.floor((maxValue - minxValue) / bucketsSize) + 1;   // --> Why is it necessary to add 1 when calculating the number of elements in the bucket?  I do not really understand.
  const bukets: number[][] = [];
  for (let i: number = 0; i < buketCount; i++) {
    bukets[i] = [];
  }
....

If you see, I hope to help me explain, thank you very much

zhyd1997 commented 3 years ago

Why is it necessary to add 1 when calculating the number of elements in the bucket? I do not really understand.

it is related to for (let i = 0; i < bucketCount; i++),

i is less than bucketCount,

it can not be equal to that,

if we don't plus 1, we could lose one elements in bucket.

PachVerb commented 3 years ago

Why is it necessary to add 1 when calculating the number of elements in the bucket? I do not really understand.

it is related to for (let i = 0; i < bucketCount; i++),

i is less than bucketCount,

it can not be equal to that,

if we don't plus 1, we could lose one elements in bucket.

Yes, I seem to understand. Thank you.