Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an integer array in-place in Python?

how can one sort an integer array (not a list) in-place in Python 2.6? Is there a suitable function in one of the standard libraries?

In other words, I'm looking for a function that would do something like this:

>>> a = array.array('i', [1, 3, 2])
>>> some_function(a)
>>> a
array('i', [1, 2, 3])

Thanks in advance!

like image 802
Bolo Avatar asked Apr 04 '11 14:04

Bolo


3 Answers

Well, you can't do it with array.array, but you can with numpy.array:

In [3]: a = numpy.array([0,1,3,2], dtype=numpy.int)

In [4]: a.sort()

In [5]: a
Out[5]: array([0, 1, 2, 3])

Or you can convert directly from an array.array if you have that already:

a = array.array('i', [1, 3, 2])
a = numpy.array(a)
like image 77
Andrew Jaffe Avatar answered Oct 17 '22 02:10

Andrew Jaffe


@steven mentioned numpy.

Copies vs. in-place operation
-----------------------------
Most of the functions in `numpy` return a copy of the array argument
(e.g., `sort`).  In-place versions of these functions are often
available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
Exceptions to this rule are documented.
like image 23
lysdexia Avatar answered Oct 17 '22 01:10

lysdexia


Looking at the array docs, I don't see a method for sorting. I think the following is about as close as you can get using standard functions, although it is really clobbering the old object with a new one with the same name:

import array
a = array.array('i', [1,3,2])
a = array.array('i', sorted(a))

Or, you could write your own.

With the extra information from the comments that you're maxing out memory, this seems inapplicable for your situation; the numpy solution is the way to go. However, I'll leave this up for reference.

like image 20
GreenMatt Avatar answered Oct 17 '22 01:10

GreenMatt