阅读量:2
1.递归算法
1.1.C#递归算法计算阶乘的方法
using System; namespace C_Sharp_Example { public class Program { /// <summary> /// 阶乘:一个正整数的阶乘Factorial是所有小于以及等于该数的正整数的积,0的阶乘是1,n的阶乘是n! /// </summary> public static void Main() { int result = Factorial(5); Console.WriteLine("5的阶乘是:"+result); Console.ReadLine(); } private static int Factorial(int v) { if(v == 0 || v == 1) { return 1; } else { return v * Factorial(v-1); } } } }
1.2.C#递归算法计算数组的和
using System; namespace C_Sharp_Example { public class Program { /// <summary> /// 数组求和 /// </summary> public static void Main() { int[] numbers = { 1,2,3,4,5}; int sum = ArraySum(numbers,0); Console.WriteLine("数组的和是:"+sum); Console.ReadLine(); } private static int ArraySum(int[] arr, int v) { if(v>=arr.Length) { return 0; } else { return arr[v] + ArraySum(arr, v + 1); } } } }
1.3.C#递归算法实现斐波那契数列第三十位数字
using System; namespace C_Sharp_Example { public class Program { /// <summary> /// 实现斐波那契数列的第三十位,已知斐波那契数列1,1,2,3,5,8,自身计算前二个之和 /// </summary> public static void Main() { int n = 30; int result = feibonaqi(30); Console.WriteLine("斐波那契数列第三十位是:"+result); Console.ReadLine(); } private static int feibonaqi(int v) { if(v <= 0) { return 0; } else if(v > 0 && v <=2) { return 1; } else { return feibonaqi(v - 1) + feibonaqi(v - 2); } } } }
1.4.C#递归算法计算1-100的和
using System; namespace C_Sharp_Example { public class Program { /// <summary> /// 计算1-100-sum /// </summary> public static void Main() { int result = SumNumber(100); Console.WriteLine("1+2+3+4+...+100="+result); Console.ReadLine(); } private static int SumNumber(int v) { if(v ==1) { return 1; } else { return v + SumNumber(v-1); } } } }
2.排序算法
2.1.冒泡排序算法
using System; namespace C_Sharp_Example { public class Program { /// <summary> /// 双重循环方式实现冒泡排序 /// </summary> public static void Main() { int[] arr = { 1,6,4,2,3,9,8,0,7}; int arrLength = arr.Length; for(int i =0; i< arr.Length -1; i++) { for(int j=0;j<arr.Length-i-1;j++) { if(arr[j]>arr[j+1]) { int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } } Console.WriteLine("排序后的顺序"+string.Join(",",arr)); Console.ReadLine(); } } }
2.2. 使用递归算法实现冒牌排序
using System; namespace C_Sharp_Example { public class Program { /// <summary> /// 递归方式实现冒泡排序 /// </summary> public static void RecursiveBubbleSort(int[] arr, int arrLength) { if (arrLength == 1) return; for(int i=0; i<arrLength-1;i++) { if(arr[i] > arr[i+1]) { int tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; } } RecursiveBubbleSort(arr,arrLength-1); } private static void RecursiveBubbleSortRun() { int[] arr = { 1,6,4,2,3,9,8,0,7}; int arrLength = arr.Length; RecursiveBubbleSort(arr,arrLength); Console.WriteLine("排序后的结果"+string.Join(",",arr)); Console.ReadLine(); } } }
更新中 ~~~ 创作不易,喜欢点赞收藏加关注 ❤