【问题标题】:Merge two sorted arrays into one sorted array将两个排序数组合并为一个排序数组
【发布时间】:2011-02-20 22:41:59
【问题描述】:

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

【问题讨论】:

  • 是的.. 我是 Matlab 新手,我正在努力寻找答案:(
  • 你能帮我解决这个问题吗?我无法解决这个问题。我是 matlab 和一般编程的新手

标签: arrays sorting matlab


【解决方案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

【讨论】:

  • 非常感谢您的回答。如何更改它以按降序显示数组?
  • fliplr 函数将反转一个数组。
  • @Sandeep:正如SORT 的文档中所述,您可以添加可选的'descend' 参数。
  • 再次感谢.. 我只是在 matlab 中为此编写一个程序,而不使用该函数。因为我也需要在我自己的程序中实现这一点。
  • @nibot,你能帮我完成这个程序吗?
【解决方案2】:
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;

}

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2021-12-28
    • 2011-09-17
    相关资源
    最近更新 更多