Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the quickest way to determine if an array is sorted?

Tags:

This may seem like a duplicate of Check whether non-index column sorted in Pandas

I read that post and all the answers. No one (save one answer) addresses using numpy. It's all focused on python lists. By asking a similar question with the numpy tag, I believe I'll get a different class of answers. That said, on to the question.


consider two arrays a and b. b is sorted while a is not.

a = np.array([2, 1, 3, 0])

b = np.arange(4)

I've written this function to determine sorted-ness

def is_sorted(x):
    return (np.arange(len(x)) == np.argsort(x)).all()

What else can I do to improve on this idea? What is the quickest pandas or numpy algorithm to determine if a pd.Series or np.ndarray is sorted?


is_sorted(a)

False  

is_sorted(b)

True  

like image 389
piRSquared Avatar asked Dec 24 '16 02:12

piRSquared


1 Answers

it is O(nlogn) to sort an array, but to tell if an array is already sorted it only takes O(n).

is_sorted = lambda x: (np.diff(x)>=0).all()
like image 57
Da Qi Avatar answered Sep 24 '22 16:09

Da Qi