1、递归算法运用
一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少
public class MainClass { public static void Main() { Console.WriteLine(Foo(30)); } public static int Foo(int i) { if (i <= 0) return 0; else if (i > 0 && i <= 2) return 1; else return Foo(i - 1) + Foo(i - 2); } }
2、冒泡排序算法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void Bubble() { int[] array = new int[] { 52, 14, 8, 65, 2, 41, 59, 12 }; int temp = 0; for (int i = 0; i < array.Length - 1; i++) { bool isSort = true; for (int j = i + 1; j < array.Length; j++) { if (array[j] < array[i])//每次将后面的与前面的[i]比,小则往前冒泡 { temp = array[i]; array[i] = array[j]; array[j] = temp; isSort = false; } } if (isSort) //已经是(从小到大)排好序的,那么就不用再比较了,提高性能 { break; } } for (int i = 0; i < array.Length; i++) { Console.Write(array[i] + " "); } }
算法的时间复杂度为O(n2)。
冒泡有一个最大的问题就是这种算法不管不管你有序还是没序,闭着眼睛把你循环比较了再说。
比如我举个数组例子:[ 9,8,7,6,5 ],一个有序的数组,根本不需要排序,它仍然是双层循环一个不少的把数据遍历干净,这其实就是做了没必要做的事情,属于浪费资源。
我们可以设定一个临时遍历来标记该数组是否已经有序,如果有序了就不用遍历了。
更多参考:【数据结构与算法】这或许是东半球分析十大排序算法最好的一篇文章
3、分析程序输出
1、当使用new B()创建B的实例时,产生什么输出?
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class A { public A() { PrintFields(); } public virtual void PrintFields() { } } class B : A { int x = 1; int y; public B() { y = -1; } public override void PrintFields() { Console.WriteLine("x={0},y={1}", x, y); } }
答:X=1,Y=0;
因为new B()先调用基类的构造函数A(),进来调用PrintFields(),它被B重写了,此时输出x=1,而y还未赋值。
2、以下代码输出:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class A { public static int X; static A() { X = B.Y + 1; } } class B { public static int Y = A.X + 1; static B() { } static void Main() { Console.WriteLine("X={0},Y={1}", A.X, B.Y); } }
答:x=1,y=2
首先执行main(),由于 A 有构造函数,所以先执行 X = B.Y + 1,而此时 Y 还是默认的初始值 0,所以 X = 1, 而后在取 B.Y 时,执行 Y = A.X + 1 , 将 Y 变为 2
4、产生一个长度100的int数组,并向其中随机插入1-100,并且不能重复
采用list和循环
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int[] intArr=new int[100]; ArrayList myList=new ArrayList(); Random rnd=new Random(); while(myList.Count<100) { int num=rnd.Next(1,101); if(!myList.Contains(num)) myList.Add(num); } for(int i=0;i<100;i++) intArr[i]=(int)myList[i];