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
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?
Array.prototype.sort()
? \$\endgroup\$if (array.includes(array[i])) {...}
? Won't that ALWAYS be true? After allarray
will always includearray[i]
, right as long asi
is within the length of the array? I guess I really don't understand what you're trying to accomplish. I've asked and you've not added any description of the purpose or objective of the sort algorithm. For example, the ONLY place you usemin
is hereMath.abs(max-min)
. What's the point of that. I guess I will give up until you add enough explanation to understand what you're trying to do. \$\endgroup\$min
andmax
? Assumingmax
is the largest element in the array, the problem is you're considering the values, unlike most other sorting algorithms. So if the array has[12341231, 143]
as input, you're doing some 12341231 more loops than a typical sort algorithm which would finish in about 4 iterations even if it was quadratic. Complexity for your approach would be non-polynomial. Beyond that,array.includes(array[i])
needlessly loops over the whole array, for every number from 0 to the max value, if things weren't bad enough. \$\endgroup\$newArray.splice(i, 1);
also has O(n) time complexity, so even if you could toss out all of the "loop up to the max" business, this is still quadratic. Even with that simplification, given all the restrictions on the input, you're better off with any canonical sort like bubble sort. As wiith jfriend00, I'm confused about what/why. \$\endgroup\$