piRSquared
piRSquared

Reputation: 294498

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

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  

Upvotes: 5

Views: 1787

Answers (1)

Da Qi
Da Qi

Reputation: 635

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()

Upvotes: 4

Related Questions