DEV Community

Discussion on: Bubble sort

Collapse
 
efleurine profile image
Emmanuel

With const next = inner + 1 won't you go out of range when inner = length - 1?

How did you do the animation?

Collapse
 
jamesrweb profile image
James Robb • Edited

It won't go out of range since the const next = inner + 1; will return undefined when we try to do a lookup on output[next] for the last item in the iterable.

For example:

const x = [1, 2, 3];
console.log(x[0], x[1], x[2], x[3]); // 1, 2, 3, undefined
console.log(x[2] > x[3]); // false

This being the case no swap happens and no error throws, in other languages it would though but this is JavaScript and so we don't need to mitigate anything here.

I got the animation from Geeks for Geeks.

Collapse
 
efleurine profile image
Emmanuel

OK thanks for the explanation. Good series it is a great refresher

Thread Thread
 
jamesrweb profile image
James Robb

All good. Glad you’ve been enjoying the series so far!