简单算法
冒泡排序
// 冒泡排序加去重 public static int[] DistinctAndOrder(int[] OldArray) { if (OldArray != null && OldArray.Length > 0) { //排序 for (int i = 0; i < OldArray.Length - 1; i++) { for (int j = 0; j < OldArray.Length - i - 1; j++) { if (OldArray[j] > OldArray[j + 1]) { int temp = OldArray[j]; OldArray[j] = OldArray[j + 1]; OldArray[j + 1] = temp; } } } //去重 // return OldArray.Distinct().ToArray(); List<int> NewArray = new List<int>(); for (int i = 0; i < OldArray.Length-1; i++) { if (OldArray[i] != OldArray[i + 1]) { if (i == OldArray.Length - 2) { NewArray.Add(OldArray[i]); NewArray.Add(OldArray[i+1]); } else { NewArray.Add(OldArray[i]); } } } return NewArray.ToArray(); } else { return new int[] { }; } }
int[] Ints =new int[] { 2, 3, 6, 2, 8, 9, 1, 2, 6, 8, 4 }; Console.WriteLine($"排序前:{string.Join(",", Ints)}"); var NewInts= TestClass.DistinctAndOrder(Ints); Console.WriteLine($"排序后:{string.Join(",", Ints)}"); Console.WriteLine($"去重后:{string.Join(",", NewInts)}");
递归算法
//递归 public static int? DiGui(int n) { if (n > 0) { if (n == 1) return 1; else if (n == 2) return 1; else return DiGui(n - 1) + DiGui(n - 2); } else { return null; } }
//测试递归 1、1、2、3、5、8、13、21...... Console.WriteLine("递归测试"); Console.WriteLine($"Fn(1)=>{TestClass.DiGui(1)}" ); Console.WriteLine($"Fn(2)=>{TestClass.DiGui(2)}"); Console.WriteLine($"Fn(3)=>{TestClass.DiGui(3)}"); Console.WriteLine($"Fn(4)=>{TestClass.DiGui(4)}"); Console.WriteLine($"Fn(30)=>{TestClass.DiGui(30)}");
喜欢 C#、SQL、Web