1.递归
private void Start(){Fun(0);}/// <summary>/// 递归函数,自己调用自己/// </summary>void Fun(int a){//4.结束条件if (a > 10){return;}//2.完成要求,打印Debug.Log(a);//3.完成递归变化,作为判断条件++a;//1.构造递归Fun(a);}
练习1:使用递归求1!+2!+3!+4!+5!+……+10!
private void Start(){Debug.Log(FunJieCheng(10));} int FunJieCheng(int a){if (a == 1) { return 1; }int result = 1;for (int i = 1; i <= a; i++){result *= i;}return result + FunJieCheng(a - 1);}
练习2:一根竹竿长100m,每天砍掉一半,求第十天它的长度是多少
private void Start(){Debug.Log(FunJieCheng(0));}float j = 100f;float FunJieCheng(int a){if(a > 10){Debug.Log(j);return j;}j = j / 2;++a;Debug.Log(j);return FunJieCheng(a);}
2.冒泡排序:
bool isSort = false;int[] arry = {8,9,3,4,2,6};//第三步,有几个数就进行几轮for (int j = 0; j < arry.Length; j++){isSort = false;//第一步对比i和i+1相邻两个数//!!!!!!!!!!!!!!!!!!!!! 确实位置的数字不用继续比较 !!!!!!!!!!!!!!!!!!!!!!!!!!//!!!!!!!!!!!!!!!!!!!!! 每完成j轮,后面位置的数就不用比较了 !!!!!!!!!!!!!!!!!for (int i = 0; i < arry.Length - 1- j; i++){//如果i大于i+1,交换他们的位置if (arry[i] > arry[i + 1]){isSort = true;//第二步,交换位置int temp = arry[i];arry[i] = arry[i + 1];arry[i + 1] = temp;}}//每一轮结束后,如果isSort还是false,就说明不需要在排序了!!!!!!!!!!!!!!!!!!if(!isSort){break;}}for (int i = 0; i < arry.Length; i++){Debug.Log(arry[i]);}
3.选择排序
int[] arry = {8,3,7,4,5,6};//第五步,遍历j轮for (int j = 0; j < arry.Length; j++){//第一步声明中间商记录索引int index = 0;//第二步 依次比较(去掉已经放好的位置)for (int i = 0; i < arry.Length - j; i++){//第三步找出极值if (arry[index] < arry[i]){index = i;}}//第四步。把极大值放到目标位置//length - 1 - 轮数//如果当前最大值就在目标位置,不需要操作if (index != arry.Length - j){int temp = arry[index];arry[index] = arry[arry.Length - 1 - j];arry[arry.Length - 1 - j] = temp;}}