C#的一些算法

1.百元百鸡

protected void Page_Load(object sender, EventArgs e)
    {
        const int totalChicken = 100;//100只鸡
        const int totalMoney = 100;  //100文钱
        const int xMoney = 5;        //公鸡每只5文钱
        const int yMoney = 3;        //母鸡每只3文钱
        const int zMoney = 1;        //定义买小鸡的1文钱
        const int zNumber = 3;       //1文钱要买3只小鸡
        for (int x = 0; x <= totalChicken; x++)
        {
            for (int y = 0; y <= totalChicken; y++)
            {
                int z = totalChicken - x - y;  //计算小鸡的数量
                if (z % zNumber == 0) continue;//小鸡的数量是3的倍数才可能是正确答案
                z /= zNumber;
                int sumNumber = x * xMoney + y * yMoney + z * zMoney;
                if (sumNumber == totalMoney)
                {
                    Response.Write("公鸡数量是" + x.ToString() + "只,母鸡数量是" + y.ToString() + "只,小鸡的数量是" + (z * zNumber).ToString() +"只<br/>");
                }
            }
        }
    }

 

2.   简单的循环计数

protected void Page_Load(object sender, EventArgs e)
    {
        int total = 0;
        int i = 0;
        while (total <= 1000)
        {
            i++;
            total += i;
            Response.Write("1加到" + i + "等于" + total + "<br/>");
        }
    }

 

3.    从小到大的排序号码

 protected void Page_Load(object sender, EventArgs e)
    {
        int[] Sum = { 1, 5, 8, 17, 21, 10, 26 };
        for (int i = 0; i < Sum.Length - 1; i++)
        {
            for (int j = i + 1; j < Sum.Length; j++)
            {
                if (Sum[j] < Sum[i])
                {
                    int max = Sum[i];
                    Sum[i] = Sum[j];
                    Sum[j] = max;
                }
            }
        }
        Response.Write("排序后的结果如下:" + "<br/>");
        for (int d = 0; d < Sum.Length; d++)
            Response.Write(Sum[d].ToString());
    }

4.   经典算法之歌德巴赫猜想的算法

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("输入一个大于6的偶数:");  //提示输入信息
            int intNum = Convert.ToInt32(Console.ReadLine()); //记录输入的数字
            bool blFlag = ISGDBHArith(intNum);    //判断是否符合哥德巴赫猜想
            if (blFlag)         //如果为true,说明符合,并输出信息
            {
                Console.WriteLine("{0}能写成两个素数的和,所以其符合哥德巴赫猜想。", intNum);
            }
            else
            {
                Console.WriteLine("猜想错误。");
            }
            Console.ReadLine();
        }
        #region  判断一个数是否是素数
        /// <summary>
        /// 判断一个数是否是素数
        /// </summary>
        /// <param name="intNum">要判断的数</param>
        /// <returns>如果是,返回true,否则,返回false</returns>
        static bool IsPrimeNumber(int intNum)
        {
            bool blFlag = true;       //标识是否是素数
            if (intNum == 1 || intNum == 2)     //判断输入的数字是否是1或者2
                blFlag = true;       //为bool类型变量赋值
            else
            {
                int sqr = Convert.ToInt32(Math.Sqrt(intNum)); //对要判断的数字进行开方运算
                for (int i = sqr; i >= 2; i--)     //从开方后的数进行循环
                {
                    if (intNum % i == 0)     //对要判断的数字和指定数字进行求余运算
                    {
                        blFlag = false;     //如果余数为0,说明不是素数
                    }
                }
            }
            return blFlag;        //返回bool型变量
        }
        #endregion
        #region 判断一个数是否符合哥德巴赫猜想
        /// <summary>
        /// 判断一个数是否符合哥德巴赫猜想
        /// </summary>
        /// <param name="intNum">要判断的数</param>
        /// <returns>如果符合,返回true,否则,返回false</returns>
        static bool ISGDBHArith(int intNum)
        {
            bool blFlag = false;       //标识是否符合哥德巴赫猜想
            if (intNum % 2 == 0 && intNum > 6)    //对要判断的数字进行判断
            {
                for (int i = 1; i <= intNum / 2; i++)
                {
                    bool bl1 = IsPrimeNumber(i);   //判断i是否为素数
                    bool bl2 = IsPrimeNumber(intNum - i);  //判断intNum-i是否为素数
                    if (bl1 & bl2)
                    {
                        //输出等式
                        Console.WriteLine("{0}={1}+{2}", intNum, i, intNum - i);
                        blFlag = true;      //符合哥德巴赫猜想
                    }
                }
            }
            return blFlag;        //返回bool型变量
        }
        #endregion
    }

 

5.    经典问题之约瑟夫环问题(使用数组解决)

class Program
    {
        static void Main(string[] args)
        {
            int[] intPers = Jose(12, 3, 4);            //调用自定义方法解决约瑟夫环问题
            Console.WriteLine("出列顺序:");
            for (int i = 0; i < intPers.Length; i++)
            {
                Console.Write(intPers[i] + " ");    //输出出列顺序
            }
            Console.ReadLine();
        }
        #region 约瑟夫环问题算法
        /// <summary>
        /// 约瑟夫环问题算法
        /// </summary>
        /// <param name="total">总人数</param>
        /// <param name="start">开始报数的人</param>
        /// <param name="alter">要出列的人</param>
        /// <returns>返回一个int类型的一维数组</returns>
        static int[] Jose(int total, int start, int alter)
        {
            int j, k = 0;
            //intCounts数组存储按出列顺序的数据,以当结果返回
            int[] intCounts = new int[total + 1];
            //intPers数组存储初始数据
            int[] intPers = new int[total + 1];
            //对数组intPers赋初值,第一个人序号为0,第二人为1,依此下去
            for (int i = 0; i < total; i++)
            {
                intPers[i] = i;
            }
            //按出列次序依次存于数组intCounts中
            for (int i = total; i >= 2; i--)
            {
                start = (start + alter - 1) % i;
                if (start == 0)
                    start = i;
                intCounts[k] = intPers[start];
                k++;
                for (j = start + 1; j <= i; j++)
                    intPers[j - 1] = intPers[j];
            }
            intCounts[k] = intPers[1];
            //结果返回
            return intCounts;
        }
        #endregion
    }

6.      数组与算法之冒泡排序

 class Program
    {
        static void Main(string[] args)
        {
            int[] Sum = { 1, 8, 5, 17, 21, 10, 26 };
            Sort(Sum);//调用自定义方法Sort输出冒泡排序后的数组成员
            string[] firstNames = { "房大伟", "顾丽丽", "顾丽娇", "顾丽花" };
              Console.WriteLine("正常顺序输出用户名:");
            for (int i = 0; i < firstNames.Length; i++)
                Console.WriteLine("Name:{0}\t", firstNames[i]);
            Console.WriteLine("\n");
            Array.Clear(firstNames, 1, 3);
            Console.WriteLine("输出除房大伟以外的用户名:");
            for (int i = 0; i < firstNames.Length; i++)
                Console.WriteLine("Name:{0}\t", firstNames[i]);
            Console.WriteLine("\n");

        }
        static void Sort(int[] list)//数组作为参数
        {
            int i, j, temp;
            bool done = false;
            j = 1;
            while ((j < list.Length) && (!done))//判断长度
            {
                done = true;
                for (i = 0; i < list.Length - j; i++)
                {
                    if (list[i] > list[i + 1])
                    {
                        done = false;
                        temp = list[i];
                        list[i] = list[i + 1];//交换数据
                        list[i + 1] = temp;
                    }
                }
                j++;
            }
            Console.Write("\n排序结果如下:\n");
            for (int d = 0; d < list.Length; d++)
                Console.Write(list[d]+"\n");
            Console.Write("\n\n");
        }
    }

7.  冒泡排序的改进——快速排序算法

 class Program
    {
        static void Main(string[] args)
        {
            int[] data = new Int32[] { 2, 2, 5, 4, 7, 8, 5, 6, 1, 1 };//创建一个一维数组
            QuickRun(data, 0, data.Length - 1);//进行快速排序
            for (int i = 0; i < data.Length; i++)
                Console.Write("{0},",data[i]);
            Console.Read();
        }
        /// <summary>
        /// 快速排序算法
        /// </summary>
        /// <param name="data">排序数组</param>
        /// <param name="low">排序上限</param>
        /// <param name="high">排序下限</param>
        static void QuickRun(int[] data, int low, int high)
        {
            //简单设定中间值,并以此为一趟快排的分割点
            //注意这里是一个简单的算法,如果想对这个算法优化的话,可以采取随机的方法来获取分割点
            int middle = data[(low + high) / 2];
            int i = low;//设定移动上标
            int j = high;//设定移动下标
            do//直至分割出两个序列
            {
                while (data[i] < middle && i < high)//扫描中值左边元素
                    i++;
                while (data[j] > middle && j > low)//扫描值右边元素
                    j--;
                if (i <= j)//找到了一对可以交换的值
                {
                    int temp = data[i];
                    data[i] = data[j];
                    data[j] = temp;
                    i++;
                    j--;
                }
            } while (i<=j);
            if (j > low)//递归对比分割点元素都小的那个序列时行快速排序
                QuickRun(data, low, j);
            if (i < high)//递归对比分割点元素都大的那个序列时行快速排序
                QuickRun(data, i, high);
        }
    }

8.    冒泡排序的改进——快速排序算法

static void Main(string[] args)
        {
            //测试序列,实际系统中,如果得到乱序序列则应该先使用排序算法进行排序
            int[] data = new int[] { 0, 2, 3, 4, 6, 7, 8, 10 };
            Console.WriteLine("测试序列为");
            for (int i = 0; i < data.Length; i++)
                Console.Write("{0},", data[i]);
            Console.Write("\r\n");
            Console.WriteLine("查找元素{0},查找结果为:{1}", 3, Search(data, 3));
            Console.WriteLine("查找元素{0},查找结果为:{1}", 0, Search(data, 0));
            Console.WriteLine("查找元素{0},查找结果为:{1}", 10, Search(data, 10));
            Console.WriteLine("查找元素{0},查找结果为:{1}", 9, Search(data, 9));
            Console.Read();
        }
        /// <summary>
        /// 二分查找算法
        /// </summary>
        /// <param name="data">有序数组</param>
        /// <param name="val">查找的值</param>
        /// <returns>如果找到,则返回在数组中的下标,否则返回-1</returns>
        static int Search(int[] data, int val)
        {
            if (data.Length <= 0)//如果数组为空,则直接返回-1
                return -1;
            //设置初始上下为数组的上下限
            int low = 0;
            int high = data.Length - 1;
            while (low <= high)//循环二分查找,直接找到指定元素或者查找完毕
            {
                int middle = (low + high) / 2;//这里时行二分
                if (data[middle] == val)//找到指定元素
                    return middle;
                else if (data[middle] < val)//对二分后较大的那一半序列进行查找
                    low = middle + 1;
                else//对二分后较小的那一序列进行查找
                    high = middle - 1;
            }
            return -1;//二分结束仍没有找到指定元素
        }
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值