C#算法大纲
排序
冒泡排序
public static void BubbleSort(this int[] arry) { for (int i = 0; i < arry.Length; i++) { for (int x = 0; x < arry.Length-1-i; x++) { if (arry[x]>arry[x+1]) { int temp = arry[x]; arry[x] = arry[x + 1]; arry[x + 1] = temp; } } } arry.ToList().ForEach(item => { Console.WriteLine(item); }); }
选择排序
public static void SelectionSort(this int[] arry) { for (int i = 0; i < arry.Length - 1; i++) { //记录最小值索引 int minIndex = i; for (int j = i + 1; j < arry.Length; j++) { if (arry[j] < arry[minIndex]) { minIndex = j; } } //交互最小值 : 当前索引就是最小值时就不用交换 if (minIndex != i) { int temp = arry[i]; arry[i] = arry[minIndex]; arry[minIndex] = temp; } } arry.ToList().ForEach(item => { Console.WriteLine(item); }); }
递归
static int Recursion(int n)// { //在方法中判断n是否为1或者2如果是返回1 if (n==1) { return 1; } else if (n==2) { return 1; } //如果不是返回斐波那契公式重新调用自己直到求出所要值 return Recursion(n - 2) + Recursion(n - 1); }
计算1-2+3-4+...+m
//通过奇偶性 static int Man(int m) { int sum = 0; for (int i = 1; i <= m; i++) { if (i % 2 >0) //即为奇数 sum += i; else sum -= i; } return sum; }
二叉树
public class TreeNode { public object Data{get;set;} public TreeNode left{get;set;} public TreeNode right{get;set;} } public class Test { /// <summary> /// 建立二叉树 /// </summary> /// <param name="node"></param> public static void CreateTree(TreeNode node) { node.Data = Console.ReadLine(); if(node.Data==null||String.IsNullOrEmpty(node.Data.ToString())) return; node.left=new TreeNode(); CreateTree(node.left); if(node.left.Data==null) node.left=null; node.right=new TreeNode(); CreateTree(node.right); if(node.right.Data==null) node.right=null; } /// <summary> /// 先序遍历 /// </summary> /// <param name="node"></param> public static void preOrder(TreeNode node) { if (node == null) return; Console.WriteLine(node.Data); preOrder(node.left); preOrder(node.right); } /// <summary> /// 中序遍历 /// </summary> /// <param name="node"></param> public static void thrOrder(TreeNode node) { if (node == null) return; preOrder(node.left); Console.WriteLine(node.Data); preOrder(node.right); } /// <summary> /// 后序遍历 /// </summary> /// <param name="node"></param> public static void postOrder(TreeNode node) { if (node == null) return; preOrder(node.left); preOrder(node.right); Console.WriteLine(node.Data); } /// <summary> /// 层序遍历 /// </summary> /// <param name="node"></param> public static void levelOder(TreeNode tree) { Queue<object> queue = new Queue<object>(); queue.Enqueue(tree); while (queue.Count > 0) { TreeNode node = queue.Dequeue() as TreeNode; Console.WriteLine(node.Data); if (node.left != null) queue.Enqueue(node.left); if (node.right != null) queue.Enqueue(node.right); } } class program { static void Main(string[] args) { TreeNode node = new TreeNode(); Test.CreateTree (node); Console.WriteLine("先序"); Test.preOrder (node); Console.WriteLine("中序"); Test.thrOrder(node); Console.WriteLine("后序"); Test.postOrder(node); Console.WriteLine("层序"); Test.levelOder(node); Console.ReadLine(); }