if we have n elements with keys:{0,1,-1} and we want to sort them,how many comparison at least we have in the worst case?
- Sounds like homework. Also, you need to elaborate a bit on the problem.Shamim Hafiz - MSFT– Shamim Hafiz - MSFT2010-12-17 19:59:23 +00:00Commented Dec 17, 2010 at 19:59
- What do you mean when you say "with keys {0, 1, -1}"?aioobe– aioobe2010-12-17 20:06:24 +00:00Commented Dec 17, 2010 at 20:06
- when we want to sort cards with some keys,instead of sorting with their values we can sort them by keyselik1991– elik19912010-12-17 20:11:09 +00:00Commented Dec 17, 2010 at 20:11
Add a comment |
3 Answers
Here is a solution that runs in O(n):
- Create an array of three lists.
For each key/value entry, do
lists[entry.key + 1].append(entry)Concatenate the three lists into one long list.
This way you have no comparisons between keys.
With a small fixed number of possible values, you can sort in linear time with something like counting sort.
1 Comment
elik1991
how can i do that with a linear time?