r/programming • • Dec 02 '19

Bubble sort visualization

7.4k Upvotes

268 comments sorted by

View all comments

Show parent comments

1

u/stevethedev Dec 03 '19

That's probably true but overcomplicates the explanation. This is "foo == bar" stuff.

2

u/IdiotCharizard Dec 03 '19

I think skipping the comparisons beyond the point where you know things are sorted helps people see the idea of bubblesort "bubbling" the largest elements to the top each iteration.

1

u/stevethedev Dec 03 '19

I'm not sure I agree. I think the "don't compare things we know are good" approach, while objectively better in practice, has more complicated code that makes it harder to correlate a video to the code.

The naive-case is stupid-easy to write, and pairs well with this video.

fn sort(array):
  for i = 0 to array.length:
    for j = 0 to array.length:
      if array[i] > array[j]
        (array[i], array[j]) = (array[j], array[i])

1

u/IdiotCharizard Dec 03 '19

All you have to do to this code is add a -i to the j loop limit to get the better behaviour. That is not significant enough complexity that it should be avoided IMO.

1

u/stevethedev Dec 04 '19

I take back my previous statement. The bubble-sort shown in this graphic doesn't match the algorithm I provided earlier. It matches this one:

function videoSort(array) {
  var sorted = false;
  while (!sorted) {
    sorted = true;
    for (var i = 0; i < array.length - 1; ++i) {
      if (array[i] > array[i + 1]) {
        [array[i], array[i+1]] = [array[i+1], array[i]];
        sorted = false;
      }
    }
  }
  return array;
}

This is a much more opaque version of the bubble sort algorithm and may-as-well skip the "already sorted section."

function productionSort(array) {
  var sorted = false;
  var j = 0;
  while (!sorted) {
    sorted = true;
    ++j;
    for (var i = 0; i < array.length - j; ++i) {
      if (array[i] > array[i + 1]) {
        [array[i], array[i+1]] = [array[i+1], array[i]];
        sorted = false;
      }
    }
  }
  return array;
}

So yeah, you're right. If the video isn't using the simplest possible version of the sort, then it might as well color-code the sorted section so you know what's going on.

1

u/[deleted] Dec 07 '19

Thing of the average person you know, now realise half are dumber than that.... yes that complexity could be too much,