数组排序返回索引-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 

*/