简体   繁体   English

排序数组的合并?

[英]Merging of sorted arrays?

I have a matrix with sorted rows.我有一个带有排序行的矩阵。 Now I want kind of merge sort for my columns (I want to save numbers in a different array ascending).现在我想对我的列进行某种合并排序(我想在不同的数组中升序保存数字)。 Is there any efficient solution for that?有什么有效的解决方案吗?

I don't want to go through the hole matrix to find the minimum.我不想通过孔矩阵来找到最小值。

Well, if your rows are sorted, then you don't really need to traverse through whole matrix every time.好吧,如果您的行已排序,那么您真的不需要每次都遍历整个矩阵。 You only need to traverse 1 column each time you pick a minimal value and keep track of separate indexes for each row.每次选择最小值时只需遍历 1 列并跟踪每行的单独索引。

Meaning something like this:意思是这样的:

int newSize = rows * cols;
int[] indexes = new int[rows];
double[] sortedArray = new double[newSize];
for (int i = 0; i < newSize; i++){
    int minIndex = -1;
    double minValue = Double.MAX_VALUE;
    for (int j = 0; j < rows; j++) {
        if (indexes[j] < cols && matrix[j][indexes[j]] < minValue){
            minValue = matrix[j][indexes[j]];
            minIndex = j;
        }
    }
    sortedArray[i] = minValue;
    indexes[minIndex]++;
}

example input示例输入

double[][] matrix = {
    { 1,   4, 100},
    { 5,  10,  13},
    {11,  40,  55},
    { 0,   6,  10}
};

Output输出

[0.0, 1.0, 4.0, 5.0, 6.0, 10.0, 10.0, 11.0, 13.0, 40.0, 55.0, 100.0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM