氣泡排序
// 氣泡排序加去重 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)}");