Reputation: 415
I'm looking for a non-comparison or comparison based algorithm that can sort an array containing any permutation of the first n positive integers, which should be O(n) time complexity and O(1) space complexity.
Is there an existing algorithm that fits these specifications?
Upvotes: 8
Views: 6673
Reputation: 74410
If you have an array of size N with all integers from 1 to N present, you can use the following O(N) algorithm (Note: arrays are 1 based for the sake of this pseudocode so as not to introduce unnecessary complexity in explaining the algorithm):
Upvotes: 15
Reputation: 9422
When you are sure that all integers are between 1 and N you can use counting sort
Upvotes: 1