logoalt Hacker News

bxparkslast Thursday at 2:03 AM1 replyview on HN

I read this all the time from other people, but for me, Selection sort is the easiest to remember and implement. My next easiest would be Insertion sort.

Bubble sort doesn't click for me easily. I think it's because the terminating condition seems uglier than Selection sort or Insertion sort. I always have a little voice in the back of my mind, "Is this outer loop guaranteed to terminate?"


Replies

archargelodlast Thursday at 2:44 AM

Terminating condition in Bubble sort is "did we swap any values during this loop"? Yes -> continue, No -> list is already sorted, exit the loop.

I don't believe that insertion/selection sort is easier to grasp. Can you type it from memory, without looking it up? Here's bubble sort:

    var swapped = true
    while swapped:
      swapped = false
      for i in 0 .. list.len-2:
        if list[i] > list[i+1]:
          swap(list[i], list[i+1])
          swapped = true
show 3 replies