Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I know Bubble sort is "bad", but there's no reason to make it worse than it needs to be. The current algorithm continues comparing the items that have already "bubbled" (or in this case, "sunk") by iterating the whole length on each pass, rather than shorting the loop to only consider the unsorted portion.

A minor tweak is (changed lines marked with #):

  bubbleSort = ->
  VA.locals.swapped = true
    y = VA.length  # grab initial length
    while VA.locals.swapped
      y--          # shorten sorted portion on each pass
      VA.locals.swapped = false
      for x in [0...y] # only iterate to y
        VA.locals.x = x
        if VA.gt(x, x + 1)
          VA.swap(x, x + 1)
          VA.locals.swapped = true

  bubbleSort()


Neat. I came back 5 hours later, and the change was live. Thanks. (I was going to submit a change via Git when I got home, but you beat me to it!)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: