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 numbers in ascending orders so:
Input -> Output
indexSort([ 3, 1, 2 ], 1, 3) -> [ 1, 2, 3 ]
indexSort([ 64, 12, 9 ], 9, 64) -> [ 9, 12, 64 ]
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
elsestatement? - 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?