如何不对数组的元素进行排序,而是对数组的索引进行排序?

How do I sort not the elements of an array, but it's indexes?

本文关键字:排序 数组 索引 何不 元素      更新时间:2023-10-16

所以我有一个类似的数组:

int array[]={2, 4, 3, 1};

我想按降序排序,但要获得原始索引,这样: {1,2,0,3}我如何解决此问题,以便与任何大小的数组一起使用?另外,是否有不需要C 11的解决方案?

谢谢!

我会去做这样的事情:

std::vector<std::pair<int, int>> temp ;
int idx = 0 ;
for (auto x : array)
    temp.push_back(std::make_pair(x, idx++)) ;
std::sort(temp.begin(), temp.end()) ;

您可以轻松地摆脱(此处使用的C 11结构)的范围。无需定义STD :: PAIR的比较,默认一个可以。

如果我正确理解您,您想获得一个索引的索引列表。一种解决方案是创建一个无序的所有元素索引列表并对其进行排序。

int array[] = {2, 4, 3, 1};
int indices[] = {0, 1, 2, 3};
std::sort(indices, indices + 4, [&](int a, int b) {
    return array[b] < array[a];
});

由于您要求提供一个非C 11-way,因此您可以在lambda表达式上工作,如下所示:

int array[] = {2, 4, 3, 1};
int indices[] = {0, 1, 2, 3};
struct {
    int *array;
    bool operator()(int a, int b) const
    {
        return this->array[b] < this->array[a];
    }
} customLess = {array};
std::sort(indices, indices + 4, customLess);

两个实现都将对indices的值进行排序,但不是 array本身。结果看起来如下所示:

array == {2, 4, 3, 1}
indices == {1, 2, 0, 3}

有一个棘手,简单的解决方法:首先,您有一个未分组的数组,因此创建索引 {0, 1, 2, 3}的数组,然后使用循环对值进行分类,同时交换数组的元素根据值数组的索引:

int array[] = {2, 4, 3, 1};
int indexes[] = {0, 1, 2, 3};
for(int i(0); i < 4; i++){
    for(int j(i + 1); j < 4; j++){
        if(array[i] < array[j]){
            //sorting values
            array[i] ^= array[j];
            array[j] ^= array[i];
            array[i] ^= array[j];
            // sorting indexes
            indexes[i] ^= indexes[j];
            indexes[j] ^= indexes[i];
            indexes[i] ^= indexes[j];
        }
    }
}
cout << endl;
for(int i = 0; i < 4; i++)
    cout << array[i] << ", ";
cout << endl;
for(int i = 0; i < 4; i++)
    cout << indexes[i] << ", ";

我使用xor对数组进行排序,但是您可以使用临时变量:

int tmp = array[i]; 
array[i] = array[j];
array[j] = tmp;
tmp = indexes[i];
indexes[i] = indexes[j];
indexes[j] = tmp;

输出:

4, 3, 2, 1,
1, 2, 0, 3,

您必须在某个地方保存初始索引。一种解决方案是与结构。有点像这样:

struct IndexInt
{
    int index;
    int value;
} typename IndexInt_t
IndexInt_t array[]={{1,2}, {2,4}, {3,3}, {4,1}};

现在您可以在array[i].value之后进行排序,并通过array[i].index访问原始索引。