C#求解阶乘(递归、非递归版本)+冒泡排序算法

 

   class Test
    {

        public    struct Stack
        {
          public  int tag;
           public   int result;
        };


       private  static  int size=50;  

       private  static  Stack[] stack=new Stack[size];  //c++中,必须检验内存是否分配成功与否


        //求阶乘,调用时候,不要传入非法参数

        public static long fact(int n)
        {
            if (n <= 1) return 1;
            else return n * fact(n - 1);
        }

        //非递归版本
        public static  long fact2(int n)
        {

            if(n<=1) return 1;

            //>=2的阶乘

            int i;

            //初始化,相当于进栈

            for (i = n; i >= 0;i-- )
            {
                stack[i].tag = i;
                stack[i].result = 1;  //初始化为1
            }


            stack[0].result = stack[1].result = 1;
           
            i=2;   //从2开始处理

            do
            {
                stack[i].result = stack[i - 1].result * i;

                i++;  //退下一个

            } while (i != n);


            stack[n].result = n * stack[n - 1].result;       //最终结果

            int tmp = stack[n].result;

            return tmp;

        }

 

 

 

 

 

        //冒泡排序
        public static void BubbleSort(int[] a, int n)
        {
            int i,j,temp;

            bool flag=false;

            for(i=n-1;i>=0;i--)
            {
              flag=false;

             for(j=0;j<i;j++)
             {

              if(a[j+1]<a[j])
              {
               temp=a[j+1]; a[j+1]=a[j]; a[j]=temp;


               flag=true;
              }

            }

             if(flag==false) break;

           }


        }   //end BubbleSort

    }   //end Test

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值