如何获得排序后的索引排列如何获得、排列、索引

2023-09-11 00:03:15 作者:爱是含笑饮砒霜

由于数组 ARR = {5,16,4,7} ,我们可以通过排序排序(ARR,编曲+的sizeof( ARR)/ sizeof的(ARR [0]))。 所以现在的阵 ARR = {4,5,7,16} 并为有序阵列的排列指数 {2,0,3, 1} 。 换句话说,在改编[2] 原始数组中现在是排序数组中的位置在最小的元素 0

Given an array arr = {5, 16, 4, 7}, we can sort it through sort(arr, arr+sizeof(arr)/sizeof(arr[0])). so now the array arr = {4, 5, 7, 16} and the permutation index for the sorted array is {2, 0, 3, 1}. In other words, the arr[2] in the original array is now the smallest element in the sorted array in position 0.

有没有一种有效的方法,这样我们就可以得到置换索引?

Is there an efficient way so that we can get the permutation index?

感谢您

推荐答案

创建索引的数组,以数字0..N-1填充,并使用自定义比较排序。比较应比较原始数组项目的索引 LHS RHS 。分类索引数组这种方式重新排列它们作为置换:

Create an array of indexes, fill it with numbers 0..N-1, and sort it using a custom comparator. The comparator should compare items from the original array at indexes lhs and rhs. Sorting the array of indexes this way reorders them as a permutation:

vector<int> data = {5, 16, 4, 7};   
vector<int> index(data.size(), 0);
for (int i = 0 ; i != index.size() ; i++) {
    index[i] = i;
}
sort(index.begin(), index.end(),
    [&](const int& a, const int& b) {
        return (data[a] < data[b]);
    }
);
for (int i = 0 ; i != index.size() ; i++) {
    cout << index[i] << endl;
}

这版画 2,0,3,1

下面是ideone 一个演示。

Here is a demo on ideone.

请注意:您可以使用首页检索数据的排序顺序:

Note: you can use index to retrieve the data in sorted order:

for (int i = 0 ; i != index.size() ; i++) {
    cout << data[index[i]] << endl;
}