确定数组是否已排序的最快方法是什么?

时间:2016-12-24 02:20:08

标签: python pandas numpy

这似乎与Check whether non-index column sorted in Pandas

重复

我读了那篇文章和所有答案。没有人(保存一个答案)地址使用numpy。它都集中在python列表上。通过使用numpy标记提出类似问题,我相信我会得到不同类别的答案。那就是问题。

考虑两个数组abb排序a,而a = np.array([2, 1, 3, 0]) b = np.arange(4) 则不排序。

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

我已经写了这个函数来确定sort-ness

pandas

我还能做些什么来改进这个想法?什么是最快的numpypd.Series算法来确定np.ndarrayis_sorted(a) False 是否已排序?

is_sorted(b)

True  
package com.nova.netmanager;

import android.content.Context;
import android.net.wifi.WifiManager;

class Net {
    public boolean isWifiEnabled() {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        return wifi.isWifiEnabled();
    }
}

1 个答案:

答案 0 :(得分:2)

对数组进行排序是O(nlogn),但要判断数组是否已经排序,只需要O(n)。

is_sorted = lambda x: (np.diff(x)>=0).all()