• 数组排序返回索引-python和c++的实现


    返回一个数组排序后的索引经常在项目中用到,所以这里总结一下c++和python两种语言的实现。

    Python

    #!/usr/local/bin/python3
    
    a=[2,3,4,5,63,4,32,3]
    
    # ascending 
    #sorted
    sorted_indx = [idx for idx,v in sorted(enumerate(a), key=lambda x: x[1])]
    print("ascending sorted:", sorted_indx)
    
    #numpy
    import numpy as np
    sorted_indx = np.argsort(a)
    print("ascending argsort:", sorted_indx)
    
    
    # descending
    #sorted
    sorted_indx = [idx for idx,v in sorted(enumerate(a), key=lambda x: x[1], reverse=True)]
    print("descending sorted:", sorted_indx)
    
    #numpy
    import numpy as np
    sorted_indx = np.argsort(-np.array(a))
    print("descending argsort:", sorted_indx)
    
    ''' output
    ascending sorted: [0, 1, 7, 2, 5, 3, 6, 4]
    ascending argsort: [0 1 7 2 5 3 6 4]
    descending sorted: [4, 6, 3, 2, 5, 1, 7, 0]
    descending argsort: [4 6 3 2 5 1 7 0]
    '''

    c++

    #include <vector>
    #include <iostream>
    
    
    using namespace std;
    
    template<typename T>
    vector<int>  sort_indexes(const vector<T>  & v, bool reverse=false) {
    
        // initialize original index locations
        vector<int>  idx(v.size());
        for (int i = 0; i != idx.size(); ++i) idx[i] = i;
        
        // sort indexes based on comparing values in v
        if(reverse)
        {
            sort(idx.begin(), idx.end(),
            [& v](int i1, int i2) {return v[i1] > v[i2];});
        }else{
            sort(idx.begin(), idx.end(),
            [& v](int i1, int i2) {return v[i1] <  v[i2];});
        }
    
      return idx;
    }
    
    int main()
    {
        int arr[] = {2,3,4,5,63,4,32,3};
        vector<int> l(arr, arr+8);
        vector<int> sorted_indx;
        sorted_indx = sort_indexes(l);
        cout << "ascending sorted: ";
        for(auto e : sorted_indx)
        {
            cout << e << " ";
        }
        cout << endl;
    
        sorted_indx = sort_indexes(l, true);
        cout << "descending sorted: ";
        for(auto e : sorted_indx)
        {
            cout << e << " ";
        }
        cout << endl;
    
        return 0;
    }
    
    /*output 
    ~$ g++ -std=c++11 index_sort.cpp -o test
    ~$ ./test 
    ascending sorted: 0 1 7 2 5 3 6 4 
    descending sorted: 4 6 3 2 5 1 7 0 
    
    */
  • 相关阅读:
    Dubbo之SPI实现原理详解
    Java SPI详解
    Java是如何实现自己的SPI机制的
    Dubbo的负载均衡原理解析
    Dubbo公开课
    【todo】什么是沟子函数
    一步一图,带你走进 Netty 的世界!
    https://github.com/xiaojiaqi/k8seasy_release_page
    mysql 8.0导致5.6数据后 :ERROR 1449 (HY000): The user specified as a definer ('mysql.infoschema'@'localhost') does not exist
    Ansible 日常使用技巧
  • 原文地址:https://www.cnblogs.com/walter-xh/p/12244779.html
Copyright © 2020-2023  润新知