Bubble sort algorithm in JavaScript I'm new to JavaScript (and programming) and taking a course. I was tasked with creating a bubble sort on any array using JavaScript. Of course, since this is an algorithm challenge, no sort method allowed. After I wrote this, I looked around at other implementations of bubble sort. I only found one that used a similar algorithm. Most set a variable to true or false to exit the loop.

I'm curious if the way I've written this is valid, efficient, and even a bubble sort at all -- since I don't loop through the entire array at any point (unless edge case is the array is already sorted). I know there are tons of bubble sort questions out there, but I couldn't find one exactly like this.

//Bubble Sort algorithm practice for JavaScript class

arrayX = [1,9,-1,5,10,23,-2,7,4,5,1];

for (i = 0; i &lt;= arrayX.length-1; i++)
  {
    if (arrayX[i] &gt; arrayX[i+1])
      {
        temp = arrayX[i+1];
        arrayX[i+1] = arrayX[i];
        arrayX[i] = temp;
        i = i-2;
      }
  }
console.log(arrayX);
Let me start with the interesting question:


  Is it even a bubble sort?  


This sort is a bit like bubble sort and a bit like insertion sort. You have re-invented gnome sort, so congratulations, that's a nice coup for a beginner.

The other answers -- which state that you should not access arrays out-of-bounds, and should use var to declare local variables rather than relying on automatic declaration to save you, are correct.  To that basic advice I would add the following:


Make a sorting function that takes an array as its argument
Now that you have such a function, write test cases.  Don't forget to test already-sorted arrays, empty arrays, arrays with one, two, or three elements, arrays sorted into reverse order, and so on.


That's the basic stuff. A more advanced technique that you should start using now is 


clearly state your loop invariants in comments or, better, assertions


A loop invariant is something that you believe to be true no matter what at various points in the loop. For example, a loop invariant that you have violated is "the index is always in bounds". 

By clearly stating your invariants you can then analyze the code to see if it correctly maintains the invariants. If it does, then you have more confidence that the code is correct.

The loop invariant of bubble sort is "after n iterations, the last n elements are in their proper place".

The loop invariant of gnome sort is "everything to the left of i is sorted".


  I'm curious if the way I've written this is valid, efficient, and even a bubble sort at all 


Though the code uses poor practices that have already been discussed, it appears to be a valid sort.

It is not, as sorts go, efficient. Asking whether a bubble sort (or bubble sort variation) written in JavaScript is efficient is a bit like asking which of two pet turtles is the faster; if you care about speed then you've chosen the wrong pet.