# Is this sorting algorithm valid and able to run in O(range of input set) time?

I imagined a sorting algorithm that sorts an array in O(r) time, where r is the range. Is this already an algorithm (if so, which?), or have I made a mistake calculating the running time (probably).

1. Create an array going consecutively from the smallest element to the largest element.
2. Loop over the unsorted array and for each element mark the same element in the generated array. Since the list is sorted, we can jump to each element in O(1) time [number three is the third element in the generated array].
3. Remove all elements that are unmarked from the generated array.

If this can really run in O(r), then since for most datasets the range is not larger than the number of elements, this would be faster than merge sort or any other sorting algorithm.

• Your algorithm is close to Counting Sort Apr 4, 2016 at 23:12
• @Prateek Counting Sort should be used more often; especially when the numbers are consecutive. Apr 4, 2016 at 23:25
• Absolutely, the only thing is that we must know the range of numbers before hand. Apr 4, 2016 at 23:59
• This gets at issues of the model of running time. On a Turing Machine, you cannot jump to the $k$th element in $O(1)$ time. Maybe you can probably do so in the RAM model, not sure. Also, I think you could implement "remove all elements that are unmarked" in linear time if you're allowed to jump to memory addresses in constant time, but it's at least not immediately obvious how.
– usul
Apr 5, 2016 at 5:11
• @usul Looping over the array and remove it if it is unmarked works on a Turing Machine. Apr 5, 2016 at 22:46