Possibly bubble sort algorithm I'm trying to figure out what to call this sorting algorithm:



function sort(array) {
  array = array.slice();

  for (let i = 0; i &lt; array.length; i++) {
    for (let j = 0; j &lt; array.length - 1; j++) {
      if (array[j] &gt; array[i]) {
        //swap
        [array[i], array[j]] = [array[j], array[i]]
      }
    }
  }

  return array;
}

console.log(sort([8, 4, 5, 2, 3, 7]));




I wrote it while trying to figure out bubble sort which is a lot different. Tho will have slightly the same running time as the actual bubble sort. I might be wrong :(
To me, that's exactly Bubblesort: it takes care the largest element moves to the end of the array, and then operates on length-1 elements.

Edit: this does look quite similar to Bubblesort, but - as a diligent reader noticed - is not quite Bubblesort, as the algorithm does not compare (and swap) adjacent elements (which indeed is the main characteristic of Bubblesort). If you replace array[j] &gt; array[i] with array[j] &gt; array[j+1], you will get Bubblesort.

This implementation will fail if less than two input elements are given (0 or 1) - hint: the array is already sorted in these cases (just add an if).

A small improvement would be to add a flag in the i loop which records if any swapping happened at all - the outer for loop may terminate if the inner loop didn't perform any swaps. (Time) performance of Bubblesort is considered to be awful in comparison to other algorithms, but it must be noted it's the fastest algorithm on an already sorted array - if you add that flag ;)