zoukankan      html  css  js  c++  java
  • 数组排序返回索引-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 
    
    */
  • 相关阅读:
    Portal技术介绍
    DBlibrary 常用函数
    【转】如何让你的WinForm嵌入桌面
    【转】Windows快捷方式文件格式解析(中文)
    合理安排时间
    javascript脚本压缩工具JSEncoder实现
    【转及整理】C#管理快捷方式文件创建
    【转】房产崩盘路线图
    【转】关于个人知识管理(PKM)的一些基本概念
    Javascript代码压缩、加密算法的破解分析及工具实现
  • 原文地址:https://www.cnblogs.com/walter-xh/p/12244779.html
Copyright © 2011-2022 走看看