在保留原始索引的同时对值进行更快的排序

faster way to sort on value while retaining original index

本文关键字:排序 原始 保留 索引      更新时间:2023-10-16

我希望得到一些帮助,以更快的方式对值进行排序,同时保留原始顺序上的键。我宁愿避免使用boost,它不需要是一个稳定的排序。这是我想出的代码,它的工作,但缓慢和低效。排序完成后,我不需要保留地图。

struct column_record
{
    int index;
    float value;
};
// sort each column on value while retaining index
column_record *preprocess_matrix(float *value, int m, int n)
{
    std::multimap<float,int> column_map;
    column_record *matrix = new column_record[m*n];
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
        {
            column_map.insert(std::pair<float,int>(value[m*i+j],j));
        }
        int j = 0;
        for (std::multimap<float,int>::iterator it=column_map.begin(); it!=column_map.end(); it++)
        {
            matrix[m*i+j].index = (*it).second;
            matrix[m*i+j].value = (*it).first;
            j++;
        }
        column_map.clear();
    }
    return matrix;
}

假设可以返回column_record对象的数组,我不认为您的解决方案特别低效。也许您可以通过使用STL算法使其更简洁,并消除对std::multimap的需求:

bool compare_column_records(const column_record& lhs, const column_record& rhs)
{
    return lhs.value < rhs.value;
}
column_record* preprocess_matrix(float* value, int m, int n)
{
    const int num_elements = m * n;
    column_record* matrix = new column_record[num_elements];
    for (int i = 0; i < num_elements; ++i)
    {
        // not sure what you mean by index; it looks like you want column index only?
        matrix[i].index = i;
        matrix[i].value = value[i];
    }
    std::sort(matrix, matrix + num_elements, compare_column_records);
    return matrix;
}

首先,我看到您使用一个一维数组来模拟您的矩阵。第一步,我将创建一个索引为

的新数组
int count = m*n;
int *indices = new int[count];
for (i=0;i<count;i++) indices[i] = i;

(我有一段时间没有用c++编程了,所以我不知道你是否可以在飞行中进行初始化)。

你可以改变一个排序方法来接受你的原始矩阵和新创建的索引数组,并对其进行排序。

为了使事情更容易,我将矩阵转置来排序行(连续索引),而不是列。