打算好好学习下数据结构,记录一下各示例的算法
合并数组的算法一:
/// <summary>
/// 已知两个数组是从小到大排列,要求将两个数组合成一个数组,且新数组也是从小到大排列
/// </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
public static int[] Func1(int[] m, int[] n)
{
if (m == null || n == null)
{
throw new ArgumentException("传入的数组不能为空!");
}
int[] result = new int[m.Length + n.Length];
int indexm = 0;
int indexn = 0;
for (int i = 0; i < result.Length; i++)
{
if (indexm >= m.Length || indexn >= n.Length)
{
break;
}
if (m[indexm] > n[indexn])
{
result[i] = n[indexn++];
}
else if (m[indexm] < n[indexn])
{
result[i] = m[indexm++];
}
else
{
result[i] = m[indexm++];
indexn++;
}
}
if (indexm >= m.Length)
{
for (int i = indexm + indexn; i < result.Length; i++)
{
result[i] = n[indexn++];
}
}
if (indexn >= n.Length)
{
for (int i = indexn + indexm; i < result.Length; i++)
{
result[i] = m[indexm++];
}
}
return result;
}
合并数组的算法二:
/// <summary>
/// 已知两个数组是从小到大排列,要求将两个数组合成一个数组,且新数组也是从小到大排列
/// </summary>
/// <param name="SLm"></param>
/// <param name="SLn"></param>
/// <returns></returns>
public static int[] Func(int[] SLm, int[] SLn)
{
if (SLm == null || SLn == null)
{
throw new ArgumentException("传入数组不能为空!");
}
int[] result = new int[SLm.Length + SLn.Length];
int mIndex = 0;
int nIndex = 0;
for (int index = 0; index < result.Length; index++)
{
if (mIndex >= SLm.Length && nIndex >= SLn.Length)
{
break;
}
if (mIndex >= SLm.Length)
{
result[index] = SLn[nIndex++];
continue;
}
if (nIndex >= SLn.Length)
{
result[index] = SLm[mIndex++];
continue;
}
if (SLm[mIndex] < SLn[nIndex])
{
result[index] = SLm[mIndex++];
}
else if (SLm[mIndex] > SLn[nIndex])
{
result[index] = SLn[nIndex++];
}
else
{
result[index] = SLm[mIndex++];
nIndex++;
}
}
return result;
}
求阶乘的算法:
/// <summary>
/// 求一个数的阶乘
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
public static int Func2(int n)
{
if (n < 0)
{
throw new ArgumentException("不能小于0");
}
else if (n == 1 || n == 0)
{
return 1;
}
return n * Func2(n - 1);
}