0

First, let me give some context: I teach a first course in numerics for students who major in biology and mathematics. In this course, I try to give the students good habits for manipulating array of numbers, such as using the ndarray data structure of NumPy.

I am aware of the fact that no for loop should be used over a ndarray. I want to illustrate this statement with a standard sorting algorithm. Of course I know how to code this naively, and this is not what I want to do here.

I don't know how to do it with all the machinery of NumPy, but I thought I could search by myself. I found the reference page for the sort function in NumPy, which has the following signature

numpy.sort(a, axis=-1, kind='quicksort', order=None)

This page links to the source code of the function, which is useful. But then I'm lost! I don't understand where the magic happens in the following lines:

if axis is None:
    a = asanyarray(a).flatten()
    axis = 0
else:
    a = asanyarray(a).copy(order="K")
a.sort(axis=axis, kind=kind, order=order)
return a

So my question is: what does this piece of code do?

bela83
  • 268
  • 1
  • 10
  • we don't see the values of `kind` and `order` – Jean-François Fabre Feb 27 '17 at 15:38
  • He didn't quote the function definition that accepts those parameters. – hpaulj Feb 27 '17 at 15:42
  • 1
    This function form delegates the task to method form. – hpaulj Feb 27 '17 at 15:43
  • Yes I see that, but then where is the source code of the method? – bela83 Feb 27 '17 at 15:46
  • 1
    You really want to go into the [source code](https://github.com/numpy/numpy/tree/c90d7c94fd2077d0beca48fa89a423da2b0bb663/numpy/core/src/npysort) of `ndarray.sort`? – MSeifert Feb 27 '17 at 15:50
  • @MSeifert thanks! So this is it? I should give up? The source code is either transparent (above) or cryptic (your link) ? – bela83 Feb 27 '17 at 15:55
  • @bela83 No you don't need to give up. But most performance critical code in numpy is written as template, that template is converted to a C implementation which gets compiled as extension module and that extension is called eventually by the `np.sort` function. It's not really hard to understand but it takes a fair amount of C and Python knowledge. – MSeifert Feb 27 '17 at 16:03

0 Answers0