将两个排序的数组合并为一个排序的数组

时间:2011-02-20 22:41:59

标签: arrays sorting matlab

我正在尝试编写一个Matlab函数,该函数合并包含整数的2个排序数组。输入是2个数组,每个数组按升序排列。函数应该组合这些数组的元素并生成一个输出数组,使其按升序包含输入数组的所有元素(包括多重性),输出数组也按升序排序。

2 个答案:

答案 0 :(得分:1)

MATLAB中最简单的方法是concatenate the two arrayssort

outArray = sort([in1(:); in2(:)]);

但是,如果您需要在不使用SORT的情况下创建自己的合并函数,则可以利用输入数组已经排序的事实。这是一种可行的方法:

function outArray = merge_sorted(in1,in2)
  inAll = [in1(:); flipud(in2(:))];  %# Combine the arrays, flipping the second
  N = numel(inAll);       %# The number of total input values
  iFront = 1;             %# Index for the front of the array
  iBack = N;              %# Index for the back of the array
  outArray = zeros(N,1);  %# Initialize the output array
  for iOut = 1:N                       %# Loop over the number of values
    if inAll(iFront) <= inAll(iBack)   %# If the front value is smaller ...
      outArray(iOut) = inAll(iFront);  %#    ...add it to the output ...
      iFront = iFront+1;               %#    ...and increment the front index
    else                               %# Otherwise ...
      outArray(iOut) = inAll(iBack);   %#    ...add the back value ...
      iBack = iBack-1;                 %#    ...and increment the back index
    end
  end
end

答案 1 :(得分:0)

function MergeTwoSortedArr(){
var arr1 = [23,45,67,89], arr2 = [34,40,50,87];
var temp=[];
var j=0;
var i=0;
while(temp.length ==(arr1.length + arr2.length)){
  if(arr1[i]< arr2[j]){
      temp.push(arr1[i]);
      i=== arr2.length-1?  temp.push(arr1[j]): i++;
  }else{
      temp.push(arr2[j]);
      j=== arr2.length -1 ?  temp.push(arr1[i]): j++;
  }
} 

return temp;

}