Roy Smith writes:

> In article <78192328-b31b-49d9-9cd6-ec742c092...@googlegroups.com>,
>  lokeshkopp...@gmail.com wrote:
> 
> > On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
> > > i need to write a code which can sort the list in order of 'n'
> > > without use builtin functions
> > > 
> > > can anyone help me how to do?
> > 
> >  Note:
> > the list only contains 0's,1's,2's
> > need to sort them in order of 'n'
> 
> What do you mean by "need to sort them in order of 'n'".  Are you
> saying that you need to sort them into numerical order?  Or that you
> need to running time of the algorithm to be O(n)?
> 
> I'm assuming the later, in which case this is starting to sound like
> a classic interview question.
> 
> Assuming you can accept an unstable sort, there's an easy solution.
> I'm not aware of any solution if you require a stable sort.  Perhaps
> that's enough of a hint?

Surely it's assumed that each element of the input list can be
classified as 0, 1, or 2 in O(1) time. If O(n) auxiliary space can be
allocated in O(n) time, just put the 0's in their own list in the
order they are encountered, 1's in their own list in the order they
are encountered, 2's in their own list in the order they are
encountered, then put the 0's back into the input list in the order
they are encountered in their auxiliary list, followed by the 1's,
followed by the 2's. Stable and O(n), no?

Even ( [ x for x in input if x.key == 0 ] +
       [ x for x in input if x.key == 1 ] +
       [ x for x in input if x.key == 2 ] ).
I suppose a list comprehension is not technically a function any more
than a loop is.

(Neither stability nor O(1) space has been required yet, I think.)
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to