C# 合并两个排序整形数组

        static int[] MergeTwoArray(int[] intArr1, int[] intArr2)
{
if (intArr1 == null || intArr2 == null || intArr1.Length == 0 || intArr2.Length == 0)
{
throw new Exception("Input cann't be null.");
}

for (int i = 0; i < intArr1.Length - 1; i++)
{
if (intArr1[i]>intArr1[i+1])
{
throw new Exception("The first Array is not sorted properly.");
}
}

for (int i = 0; i < intArr2.Length -1; i++)
{
if (intArr2[i]> intArr2[i+1])
{
throw new Exception("The second Array is not sorted properly.");
}
}

int[] result = new int[intArr1.Length + intArr2.Length];
int a = 0;
int b = 0;
int c = 0;

while (a<intArr1.Length && b<intArr2.Length)
{
if (intArr1[a]>intArr2[b])
{
result[c++] = intArr2[b++];
}
else
{
result[c++] = intArr1[a++];
}
}

while (a<intArr1.Length)
{
result[c++] = intArr1[a++];
}

while (b<intArr2.Length)
{
result[c++] = intArr2[b++];
}
return result;
}
posted @ 2012-02-06 09:27  Ligeance  阅读(647)  评论(0编辑  收藏  举报