合并两个数组并在c#中返回排序数组

时间:2015-06-02 07:00:52

标签: c# arrays c#-4.0

您将获得一个函数 <p:dataTable id="listTable" value="#{listBean.lazyDatalist}" var="list" paginator="true" paginatorPosition="top" rows="10" rowIndexVar="rowIndex" rowStyleClass="#{(rowIndex mod 2) eq 0 ? 'rowStyleOdd' : 'rowStyleEven'}" lazy="true"> <p:ajax event="page" listener="#{listBean.searchLazyData}"/> <p:column style="width:3%;" headerText="#{msg['userlist.dt.srNo']}"> <h:outputText value="#{list.orderCount}"></h:outputText> </p:column> <p:column style="width:7%;" headerText="#{msg['userlist.dt.EmployeeID']}"> <h:outputText value="#{list.employeeID}"/> </p:column> <p:column style="width:12%;" headerText="#{msg['userlist.dt.Name']}"> <h:outputText value="#{list.employeeName}"></h:outputText> </p:column> <p:column headerText="#{msg['userlist.dt.actionReq']}"> <h:commandLink value="#{list.actionRequired}" action="#{listBean.getDetails}" styleClass="linkStyle"></h:commandLink> </p:column> </p:dataTable> ,它将2个排序数组作为参数。第一个数组中包含mergeArrays个元素,第二个数组也有M个元素,但它的容量为M

函数2*M将数组作为参数和mergeArrays一起使用。您应该合并第二个数组中的两个数组,以便对生成的数组进行排序。

示例TestCase 0:

M

Input

1st array: {3,5,6,9,12,14,18,20,25,28}

2nd array: {30,32,34,36,38,40,42,44,46,48 }

说明:  如问题所述,第二个数组包含足够的空间来容纳第一个数组。返回合并的已排序数组。

2 个答案:

答案 0 :(得分:9)

解决方案可以是 Linq 查询:

  int[] first = new int[] { 3, 5, 6, 9, 12, 14, 18, 20, 25, 28 };
  int[] second = new int[] { 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 };

  int[] result = first
    .Concat(second)
    .OrderBy(x => x)
    .ToArray();

测试

  // 3, 5, 6, 9, 12, 14, 18, 20, 25, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48
  Console.Write(String.Join(", ", result));

它有效,但很难接受作为家庭作业解决方案。所以我希望你能用我的实现作为测试参考来详细说明自己的代码

答案 1 :(得分:3)

没有linq的解决方案:

int[] array1 = new int[] { 3, 5, 6, 9, 12, 14, 18, 20, 25, 28 };
int[] array2 = new int[] { 30, 32, 34, 36, 38, 40, 42, 44, 46, 48 };

int count1 = array1.Length;
int count2 = array2.Length;
int[] arrayResult = new int[count1 + count2];

int a = 0, b = 0;   // indexes in origin arrays
int i = 0;          // index in result array

// join
while (a < count1 && b < count2)
{
    if (array1[a] <= array2[b])
    {
        // element in first array at current index 'a'
        // is less or equals to element in second array at index 'b'
        arrayResult[i++] = array1[a++];
    }
    else
    {
        arrayResult[i++] = array2[b++];
    }
}

// tail
if (a < count1)
{
    // fill tail from first array
    for (int j = a; j < count1; j++)
    {
        arrayResult[i++] = array1[j];
    }
}
else
{
    // fill tail from second array
    for (int j = b; j < count2; j++)
    {
        arrayResult[i++] = array2[j];
    }
}

// print result
Console.WriteLine("Result is {{ {0} }}", string.Join(",", arrayResult.Select(e => e.ToString())));

结果:

{ 3,5,6,9,12,14,18,20,25,28,30,32,34,36,38,40,42,44,46,48 }

图解说明:

Merge

相关问题