欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » C# » 正文

热门阅读

求指定数的阶层与合并从小到大的数组并保持数组排序的算法

创建时间:2013年01月15日 11:24  阅读次数:(6169)
分享到:
打算好好学习下数据结构,记录一下各示例的算法

合并数组的算法一:
/// <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);
}
来源:
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论0条
  • 暂无任何评论,请留下您对本文章的看法,共同参入讨论!
发表评论:
留言人:
内  容:
请输入问题 97+11=? 的结果(结果是:108)
结  果: