Given an unsorted array of size n containing objects with ids of 0 … n-1, sort the array in place and in linear time. Assume that the objects contain large members such as binary data, so instantiating new copies of the objects is prohibitively expensive.
void linearSort(int* input, const int n) {
for (int i = 0; i < n; i++) {
while (input[i] != i) {
// swap
int swapPoint = input[i];
input[i] = input[swapPoint];
input[swapPoint] = swapPoint;
}
}
}
Is this linear? Does this sort work with any kind of array of ints? If so, why do we need quicksort anymore?
Despite the
whileloop inside thefor, this sort is linearO(n). If the while loop occurs multiple times for a givenithen for theivalues that matchswapPointthere will not execute the while loop at all.This implementation will only work for arrays of ints where there are no duplicates and the values are sequential from 0 to n-1, which is why Quicksort still is relevant being
O(n log n)because it works with non-sequential values.This can be easily tested by making the worst case:
and then using the following code:
The output will be as follows:
so you see even in the worst case where you have the
whileloop runn-1times in the first iteration of theforloop, you still only getn-1iterations of the while loop for the entire process.Further examples with random data: