DEV Community

JP Antunes
JP Antunes

Posted on

Tiniest bubble sort on the net?

I stumbled on an older dev.to post by the great Greg Bullmash that I really liked because it triggered my code-golfing nerve, and I figured I could come up with a bubble sort one-liner!

Turns out I was wrong, I need at least 4 3 lines to make tiniest working bubble sort algo on the net* but it was still a fun exercise so I'm sharing it.

const bubblie = (arr, swaps = false) => {
  arr.forEach((e,i) => { e > arr[i+1] ? ([arr[i], arr[i+1]] = [arr[i+1], arr[i]], swaps = true) : false });
  return !swaps ? arr : bubblie(arr, false);
}

*citation needed

Top comments (4)

Collapse
 
laffra profile image
Chris Laffra

Here is a non-recursive 4-liner in Python, with visualization.

def bubbleSort(L):
    for i in range(len(L)-1, 0, -1): 
        for j in xrange(i):
            if L[j]>L[j+1]:
                L[j],L[j+1] = L[j+1],L[j]
Collapse
 
jpantunes profile image
JP Antunes • Edited
That 
  Looks
   Really
     Nice! :-)

...but I'm in a good mood, so I've updated my code to only need 3 lines now ;-)

Collapse
 
pavelloz profile image
Paweł Kowalski

You guys need to figure out whats counts into LoC because i cant see any pattern there ;)

Thread Thread
 
jpantunes profile image
JP Antunes • Edited

You may very well be right :-)

imho, the function signature doesn't count as a LOC... however, in my code I set a default value in a function parameter but then use it as an argument, so I believe have to count it as a line.

The alternative would be:

const bubblie = (arr) => {
  let swaps = false;
  arr.forEach((e,i) => { e > arr[i+1] ? ([arr[i], arr[i+1]] = [arr[i+1], arr[i]], swaps = true) : false });
  return !swaps ? arr : bubblie(arr, false);
}

edit: now that I think about it one more time, I could use the fact that 'undefined' evaluates to false and then it would be just 2 lines of code :-)

const bubblie = (arr, swaps) => {
  arr.forEach((e,i) => { (e > arr[i+1]) ? ([arr[i], arr[i+1]] = [arr[i+1], arr[i]], swaps = true) : false });
  return swaps ? bubblie(arr, false) : arr;
}