Skip to main content
2 of 5
make title describe what code does instead of goals - refer to help center section "Titling your question" on https://codereview.stackexchange.com/help/how-to-ask; add tags

custom array sorting algorithm

So I came up with a "new" sorting algorithm:

function indexSort(array, min, max) {
    var newArray = Array.from({length:Math.abs(max-min)}, () => 0);
    for (let i = 0; i < max; i++) {
        if (array.includes(array[i])) {
            newArray[array[i]] = array[i];
        }
    }
    for (let i = 0; i < newArray.length; i++) {
        if (newArray[i] == 0) { 
            newArray.splice(i, 1); 
            i--;
        }
    }
    return newArray;
}

This algorithm sorts arrays, pretty slow at that, and, has, in its current state some major downsides in comparison to other sorting algorithms:

  • Only works with positive integers.
  • Has to loop over the entire array twice.
  • Doesn't allow for duplicate items.

It has probably other downsides that I cannot currently think of.

So what I want to figure out is:

  • Why is this sorting algorithm so slow?
  • Is it possible to do everything in just one loop using an else statement?
  • Why is this sort outperformed by Bubble Sort?
  • What is the big O notation of this algorithm?
  • Has this already been discovered and if so, what is the name of it?