Array Module

Tim Peters tim_one at email.msn.com
Tue Feb 1 17:25:53 EST 2000


[Gene Chiaramonte]
> Anyone else think we should add a sort() method to the array module?
>
> I do.

More generally, arrays "should" support every list method that makes sense
(other "missing" array methods include .index, .remove and .pop).  Guido is
known to accept patches <wink>.

In the case of .sort, Python's list.sort() is (for "go fast on average", "go
supernaturally fast in common special cases", and "don't go slow regardless"
reasons) a difficult algorithm requiring some of the hairiest code in the
whole implementation.  Because C isn't itself polymorphic, it can't be
reused for arrays (at least not without ugly multiple-include #ifdef
trickery).  list.sort() is constrained in that it knows nothing about the
types being sorted, but each of the 11 flavors of arrays does know that, so
a different algorithm entirely may well be better for arrays.

The product of my time and interest isn't large enough to overcome all that
<wink>.  Until it overcomes somebody else's, this is likely your best bet:

def sortarray(a, compare=None):
    """Array a -> return new sorted array of same type."""

    import array
    aslist = a.tolist()
    if compare is None:
        aslist.sort()
    else:
        aslist.sort(compare)
    return array.array(a.typecode, aslist)

The relative difference in time between this and what a native array.sort()
would take becomes smaller the larger the array (because sorting dominates
the time; the list<->array conversions are relatively cheap), up until the
extra memory use triggers paging.

if-it-wasn't-clear-the-answer-to-your-question-is-"yes"<wink>-ly
    y'rs  - tim






More information about the Python-list mailing list