一、List集合相关算法
public class List集合相关算法{/// <summary>/// 获取移除后的列表数据/// 考察内容:C#List RemoveAt(按照索引移除)、Remove(按照对象移除)/// </summary>/// <returns></returns>public static List<int> GetAfterRemoveListData(){List<int> list = new List<int>();for (int i = 1; i <= 10; i++){list.Add(i);}for (int i = 0; i < 5; i++){list.RemoveAt(i);//单独使用输出结果:2,4,6,8,10,按照索引移除list.Remove(i);//单独使用输出结果:5,6,7,8,9,10,按照对象移除}//以上两种同时使用时输出结果:6,7,9return list;}}
二、插入排序算法
public class 插入排序算法{public static void InsertionSort(int[] array){int arrayLength = array.Length;//数组长度(时间复杂度为O(n^2))for (int i = 1; i < arrayLength; ++i){//定义临时变量int temp = array[i];int j = i - 1;while (j >= 0 && array[j] > temp){array[j + 1] = array[j];j--;}array[j + 1] = temp;}}public static void InsertionSortRun(){int[] array = { 26, 15, 5, 3, 38, 36, 44, 27, 47, 2, 46, 4, 50, 19, 48 };Console.WriteLine("排序前:" + string.Join(", ", array));InsertionSort(array);Console.WriteLine("排序后:" + string.Join(", ", array));}}
三、递归算法
public class 递归算法{#region 使用C#语言编写的递归算法来计算1+2+3+4+…+100的结果/// <summary>/// 使用C#语言编写的递归算法来计算1+2+3+4+…+100的结果/// 最终输出结果是:5050/// </summary>public static void RecursiveAlgorithmSum(){int result = SumNumbers(100);Console.WriteLine("1+2+3+4+...+100 = " + result);}public static int SumNumbers(int n){if (n == 1){return 1;//递归结束条件}else{return n + SumNumbers(n - 1);}}#endregion#region C#使用递归算法来实现求解斐波纳契数列中第30位数的值/// <summary>/// 使用递归算法来实现求解斐波纳契数列中第30位数的值/// 一列数的规则如下 : 1 、 1 、 2 、 3 、 5 、 8 、 13 、 21 、 34… 求第 30 位数是多少, 用递归算法实现/// 最终输出结果为:832040/// </summary>public static void FibonacciSum(){int n = 30;int result = Fibonacci(n);Console.WriteLine("第 " + n + "位斐波那契数是:" + result);}public static int Fibonacci(int n){if (n <= 0){return 0;}else if (n > 0 && n <= 2){return 1;}else{// 递归情况:调用自身计算前两个数字之和return Fibonacci(n - 1) + Fibonacci(n - 2);}}#endregion#region C#递归算法数组求/// <summary>/// 递归算法数组求/// 最终输出结果为:259/// </summary>public static void RecursiveArraySum(){int[] numbers = { 1, 88, 66, 4, 100 };int sum = ArraySum(numbers, 0);Console.WriteLine("数组元素的总和为:" + sum);}/// <summary>/// 计算数组元素的总和/// </summary>/// <param name="arr">arr</param>/// <param name="index">index</param>/// <returns></returns>public static int ArraySum(int[] arr, int index){if (index >= arr.Length){// 基本情况:数组为空或者已经遍历完所有元素return 0;}else{// 递归调用:当前元素加上剩余元素的总和return arr[index] + ArraySum(arr, index + 1);}}#endregion#region C#递归算法计算阶乘的方法/// <summary>/// C#递归算法计算阶乘的方法/// 一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。1808年,基斯顿·卡曼引进这个表示法。/// 亦即n!=1×2×3×...×(n-1)×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。/// </summary>public static void RecursiveFactorial(){int result = Factorial(5);Console.WriteLine("5的阶乘为:" + result);//5!=120}public static int Factorial(int n){if (n == 0 || n == 1){return 1;}else{// 递归调用:当前数n乘以前面所有数的阶乘return n * Factorial(n - 1);}}#endregion}
四、堆排序算法
public class 堆排序算法{public static void HeapSort(int[] array){int arrayLength = array.Length;//构建最大堆for (int i = arrayLength / 2 - 1; i >= 0; i--)Heapify(array, arrayLength, i);//依次取出堆顶元素,并重新调整堆for (int i = arrayLength - 1; i >= 0; i--){//将堆顶元素与当前最后一个元素交换int temp = array[0];array[0] = array[i];array[i] = temp;//重新调整堆Heapify(array, i, 0);}}private static void Heapify(int[] arr, int n, int i){int largest = i; //假设父节点最大int left = 2 * i + 1; //左子节点int right = 2 * i + 2; //右子节点//如果左子节点大于父节点,则更新最大值if (left < n && arr[left] > arr[largest])largest = left;//如果右子节点大于父节点和左子节点,则更新最大值if (right < n && arr[right] > arr[largest])largest = right;//如果最大值不是当前父节点,则交换父节点和最大值,并继续向下调整堆if (largest != i){int swap = arr[i];arr[i] = arr[largest];arr[largest] = swap;Heapify(arr, n, largest);}}public static void HeapSortRun(){int[] array = { 19, 27, 46, 48, 50, 2, 4, 44, 47, 36, 38, 15, 26, 5, 3, 99, 888, 0, -1 };Console.WriteLine("排序前数组:" + string.Join(", ", array));HeapSort(array);Console.WriteLine("排序后数组:" + string.Join(", ", array));}}
五、二叉搜索树算法
public class 二叉搜索树算法{public static void BinarySearchTreeRun(){var bst = new BinarySearchTree();// 插入一些值到树中bst.Insert(50);bst.Insert(30);bst.Insert(20);bst.Insert(40);bst.Insert(70);bst.Insert(60);bst.Insert(80);bst.Insert(750);Console.WriteLine("中序遍历(打印有序数组):");bst.InorderTraversal();Console.WriteLine("\n");// 查找某些值Console.WriteLine("Search for 40: " + bst.Search(40)); // 输出: TrueConsole.WriteLine("Search for 25: " + bst.Search(25)); // 输出: FalseConsole.WriteLine("\n");// 删除某个值bst.Delete(50);Console.WriteLine("删除50后:");bst.InorderTraversal();}}/// <summary>/// 定义二叉搜索树的节点结构/// </summary>public class TreeNode{public int Value;public TreeNode Left;public TreeNode Right;public TreeNode(int value){Value = value;Left = null;Right = null;}}/// <summary>/// 定义二叉搜索树类/// </summary>public class BinarySearchTree{private TreeNode root;public BinarySearchTree(){root = null;}#region 插入节点/// <summary>/// 插入新值到二叉搜索树中/// </summary>/// <param name="value">value</param>public void Insert(int value){if (root == null){root = new TreeNode(value);}else{InsertRec(root, value);}}private void InsertRec(TreeNode node, int value){if (value < node.Value){if (node.Left == null){node.Left = new TreeNode(value);}else{InsertRec(node.Left, value);}}else if (value > node.Value){if (node.Right == null){node.Right = new TreeNode(value);}else{InsertRec(node.Right, value);}}else{//值已经存在于树中,不再插入return;}}#endregion#region 查找节点/// <summary>/// 查找某个值是否存在于二叉搜索树中/// </summary>/// <param name="value">value</param>/// <returns></returns>public bool Search(int value){return SearchRec(root, value);}private bool SearchRec(TreeNode node, int value){// 如果当前节点为空,表示未找到目标值if (node == null){return false;}// 如果找到目标值,返回trueif (node.Value == value){return true;}// 递归查找左子树或右子树if (value < node.Value){return SearchRec(node.Left, value);}else{return SearchRec(node.Right, value);}}#endregion#region 中序遍历/// <summary>/// 中序遍历(打印有序数组)/// </summary>public void InorderTraversal(){InorderTraversalRec(root);}private void InorderTraversalRec(TreeNode root){if (root != null){InorderTraversalRec(root.Left);Console.WriteLine(root.Value);InorderTraversalRec(root.Right);}}#endregion#region 删除节点/// <summary>/// 删除某个值/// </summary>/// <param name="val">val</param>public void Delete(int val){root = DeleteNode(root, val);}private TreeNode DeleteNode(TreeNode node, int val){if (node == null){return null;}if (val < node.Value){node.Left = DeleteNode(node.Left, val);}else if (val > node.Value){node.Right = DeleteNode(node.Right, val);}else{// 节点有两个子节点if (node.Left != null && node.Right != null){// 使用右子树中的最小节点替换当前节点TreeNode minNode = FindMin(node.Right);node.Value = minNode.Value;node.Right = DeleteNode(node.Right, minNode.Value);}// 节点有一个子节点或没有子节点else{TreeNode? temp = node.Left != null ? node.Left : node.Right;node = temp;}}return node;}/// <summary>/// 找到树中的最小节点/// </summary>/// <param name="node"></param>/// <returns></returns>private TreeNode FindMin(TreeNode node){while (node.Left != null){node = node.Left;}return node;}#endregion}
六、二分查找算法
public class 二分查找算法{/// <summary>/// 二分查找算法/// </summary>/// <param name="arr">arr是已排序的数组</param>/// <param name="target">target是要查找的目标值</param>/// <returns>目标值在数组中的索引,如果未找到则返回-1</returns>public static int BinarySearch(int[] arr, int target){int left = 0; // 定义左指针int right = arr.Length - 1; // 定义右指针while (left <= right){// 计算中间元素的索引int mid = left + (right - left) / 2;if (arr[mid] == target){// 如果中间元素等于目标值return mid; // 查找成功,返回索引}else if (arr[mid] < target){// 如果目标值小于中间元素,则在左半部分查找left = mid + 1;}else{// 如果目标值大于中间元素,则在右半部分查找right = mid - 1;}}// 未找到 target,返回-1return -1;}public static void BinarySearchRun(){int[] arr = { 1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59 }; //注意:这里的数组是已排序的数组int target = 31; //需要要查找的目标值int result = BinarySearch(arr, target); //调用二分查找方法if (result == -1){Console.WriteLine("元素未找到");}else{Console.WriteLine($"元素找到,索引为:{result},值为:{arr[result]}");}}}
七、归并排序算法
public class 归并排序算法{public static void MergeSort(int[] arr, int left, int right){if (left < right){// 计算中间索引int mid = (left + right) / 2;// 对左半部分数组进行归并排序MergeSort(arr, left, mid);// 对右半部分数组进行归并排序MergeSort(arr, mid + 1, right);// 合并两个有序数组Merge(arr, left, mid, right);}}public static void Merge(int[] arr, int left, int mid, int right){int n1 = mid - left + 1; // 左半部分数组的长度int n2 = right - mid; // 右半部分数组的长度// 创建临时数组int[] leftArr = new int[n1];int[] rightArr = new int[n2];// 将数据拷贝到临时数组for (int i = 0; i < n1; ++i){leftArr[i] = arr[left + i];}for (int j = 0; j < n2; ++j){rightArr[j] = arr[mid + 1 + j];}// 合并两个有序数组int k = left; // 初始化合并后的数组索引int p = 0; // 初始化左半部分数组的索引int q = 0; // 初始化右半部分数组的索引while (p < n1 && q < n2){if (leftArr[p] <= rightArr[q]){arr[k] = leftArr[p];p++;}else{arr[k] = rightArr[q];q++;}k++;}// 复制左半部分数组的剩余元素while (p < n1){arr[k] = leftArr[p];p++;k++;}// 复制右半部分数组的剩余元素while (q < n2){arr[k] = rightArr[q];q++;k++;}}public static void MergeSortRun(){int[] array = { 19, 27, 46, 48, 50, 2, 4, 44, 47, 36, 38, 15, 26, 5, 3 };Console.WriteLine("排序前数组:" + string.Join(", ", array));MergeSort(array, 0, array.Length - 1);Console.WriteLine("排序后数组:" + string.Join(", ", array));}}
八、哈希查找算法
public class 哈希查找算法{/// <summary>/// 哈希查找函数/// </summary>/// <param name="target">target</param>public static void HashSearchFunctionRun(int target){//创建一个字典来存储键值对var dic = new Dictionary<int, string>();dic.Add(1, "one");dic.Add(2, "two");dic.Add(3, "three");//查找目标值是否在Dictionary中存在//TryGetValue方法可以返回一个bool值和值,如果找到了目标值,则返回true和对应的值,否则返回false和默认值string value;if (dic.TryGetValue(target, out value)){Console.WriteLine("Found Data: " + value);}else{Console.WriteLine("Not Found Data.");}}}
九、基数排序算法
public class 基数排序算法{public static void RadixSort(int[] array){if (array == null || array.Length < 2){return;}//获取数组中的最大值,确定排序的位数int max = GetMaxValue(array);//进行基数排序for (int exp = 1; max / exp > 0; exp *= 10){CountingSort(array, exp);}}private static void CountingSort(int[] array, int exp){int arrayLength = array.Length;int[] output = new int[arrayLength];int[] count = new int[10];//统计每个桶中的元素个数for (int i = 0; i < arrayLength; i++){count[(array[i] / exp) % 10]++;}//计算每个桶中最后一个元素的位置for (int i = 1; i < 10; i++){count[i] += count[i - 1];}//从原数组中取出元素,放入到输出数组中for (int i = arrayLength - 1; i >= 0; i--){output[count[(array[i] / exp) % 10] - 1] = array[i];count[(array[i] / exp) % 10]--;}//将输出数组复制回原数组for (int i = 0; i < arrayLength; i++){array[i] = output[i];}}private static int GetMaxValue(int[] arr){int max = arr[0];for (int i = 1; i < arr.Length; i++){if (arr[i] > max){max = arr[i];}}return max;}public static void RadixSortRun(){int[] array = { 19, 27, 46, 48, 99, 888, 50, 2, 4, 44, 47, 36, 38, 15, 26, 5, 3 };Console.WriteLine("排序前数组:" + string.Join(", ", array));RadixSort(array);Console.WriteLine("排序后数组:" + string.Join(", ", array));}}
十、计数排序算法
public class 计数排序算法{public static void CountingSort(int[] array){int arrayLength = array.Length;if (arrayLength <= 1) return;int min = array[0];int max = array[0];//找出最大值和最小值for (int i = 1; i < arrayLength; i++){if (array[i] < min) min = array[i];if (array[i] > max) max = array[i];}//统计每个元素出现的次数int[] count = new int[max - min + 1];//统计每个元素出现的次数for (int i = 0; i < arrayLength; i++){count[array[i] - min]++;}//根据count数组和min值确定每个元素的起始位置for (int i = 1; i < count.Length; i++){count[i] += count[i - 1];}//存储排序结果int[] temp = new int[arrayLength];//根据count数组和min值确定每个元素在temp数组中的位置for (int i = arrayLength - 1; i >= 0; i--){int index = count[array[i] - min] - 1;temp[index] = array[i];count[array[i] - min]--;}//将排序结果复制回原数组for (int i = 0; i < arrayLength; i++){array[i] = temp[i];}}public static void CountingSortRun(){int[] array = { 19, 27, 46, 48, 50, 2, 4, 44, 47, 36, 38, 15, 26, 5, 3, 99, 888 };Console.WriteLine("排序前数组:" + string.Join(", ", array));CountingSort(array);Console.WriteLine("排序后数组:" + string.Join(", ", array));}}
十一、快速排序算法
public class 快速排序算法{public static void Sort(int[] array, int low, int high){if (low < high){//将数组分割为两部分,并返回分割点的索引int pivotIndex = Partition(array, low, high);//递归对分割后的两部分进行排序Sort(array, low, pivotIndex - 1);Sort(array, pivotIndex + 1, high);}}private static int Partition(int[] array, int low, int high){//选择最后一个元素作为基准元素int pivot = array[high];int i = low - 1;for (int j = low; j <= high - 1; j++){//如果当前元素小于等于基准元素,则将它与i+1位置的元素交换if (array[j] <= pivot){i++;Swap(array, i, j);}}//将基准元素放置到正确的位置上Swap(array, i + 1, high);return i + 1; //返回基准元素的索引}private static void Swap(int[] array, int i, int j){int temp = array[i];array[i] = array[j];array[j] = temp;}public static void QuickSortRun(){int[] array = { 2, 3, 5, 38, 19, 15, 26, 27, 36, 44, 47, 46, 50, 48, 4 };Sort(array, 0, array.Length - 1);Console.WriteLine("排序后结果:" + string.Join(", ", array));}}
十二、冒泡排序算法
public class 冒泡排序算法{/// <summary>/// 双重循环方式实现冒泡排序/// </summary>public static void BubbleSort(){int[] arr = { 1, 8, 9, 5, 6, 2, 3, 4, 7 };int arrLength = arr.Length;for (int i = 0; i < arrLength - 1; i++){for (int j = 0; j < arrLength - i - 1; j++){if (arr[j] > arr[j + 1]){//交换arr[j]和arr[j+1]的值int temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}Console.WriteLine("排序后结果:" + string.Join(", ", arr));}/// <summary>/// 递归方式实现冒泡排序/// </summary>/// <param name="arr">arr</param>/// <param name="arrLength">arrLength</param>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]){//交换arr[i]和arr[i+1]的值int temp = arr[i];arr[i] = arr[i + 1];arr[i + 1] = temp;}}RecursiveBubbleSort(arr, arrLength - 1);}public static void RecursiveBubbleSortRun(){int[] arr = { 1, 8, 9, 5, 6, 2, 3, 4, 7 };int arrLength = arr.Length;RecursiveBubbleSort(arr, arrLength);Console.WriteLine("排序后结果:" + string.Join(", ", arr));}}
十三、桶排序算法
public class 桶排序算法{public static void BucketSort(int[] array){int arrLength = array.Length;if (arrLength <= 1){return;}//确定桶的数量int maxValue = array[0], minValue = array[0];for (int i = 1; i < arrLength; i++){if (array[i] > maxValue)maxValue = array[i];if (array[i] < minValue)minValue = array[i];}int bucketCount = (maxValue - minValue) / arrLength + 1;//创建桶并将数据放入桶中List<List<int>> buckets = new List<List<int>>(bucketCount);for (int i = 0; i < bucketCount; i++){buckets.Add(new List<int>());}for (int i = 0; i < arrLength; i++){int bucketIndex = (array[i] - minValue) / arrLength;buckets[bucketIndex].Add(array[i]);}//对每个非空的桶进行排序int index = 0;for (int i = 0; i < bucketCount; i++){if (buckets[i].Count == 0){continue;}int[] tempArr = buckets[i].ToArray();Array.Sort(tempArr);foreach (int num in tempArr){array[index++] = num;}}}public static void BucketSortRun(){int[] array = { 19, 27, 46, 48, 50, 2, 4, 44, 47, 36, 38, 15, 26, 5, 3, 99, 888 };Console.WriteLine("排序前数组:" + string.Join(", ", array));BucketSort(array);Console.WriteLine("排序后数组:" + string.Join(", ", array));}}
十四、希尔排序算法
public class 希尔排序算法{public static void ShellSort(int[] array){int arrLength = array.Length;// 初始化增量(初始间隔)为数组长度的一半int gap = arrLength / 2;// 不断缩小增量,直到增量为1while (gap > 0){// 对每个子序列进行插入排序for (int i = gap; i < arrLength; i++){int temp = array[i];int j = i;// 在子序列内部进行插入排序while (j >= gap && array[j - gap] > temp){array[j] = array[j - gap];j -= gap;}array[j] = temp;}// 缩小增量gap /= 2;}}public static void ShellSortRun(){int[] array = { 19, 20, 22, 32, 34, 50, 99, 49, 1, 11, 11, 55, 35, 93, 96, 71, 70, 38, 78, 48 };Console.WriteLine("排序前数组:" + string.Join(", ", array));ShellSort(array);Console.WriteLine("排序后数组:" + string.Join(", ", array));}}
十五、线性查找算法
public class 线性查找算法{public static void LinearSearchRun(){int[] arr = { 2, 3, 4, 10, 40, 50, 100, 77, 88, 99 };int target = 100;int result = LinearSearch(arr, target);// 输出结果if (result == -1){Console.WriteLine("元素未找到");}else{Console.WriteLine($"元素在索引 {result} 处找到,index = {result}");}}/// <summary>/// 线性查找函数/// </summary>/// <param name="arr">arr</param>/// <param name="target">target</param>/// <returns></returns>public static int LinearSearch(int[] arr, int target){// 遍历数组for (int i = 0; i < arr.Length; i++){// 如果找到目标值,返回其索引if (arr[i] == target){return i;}}// 如果没有找到,则返回-1return -1;}}
十六、选择排序算法
public class 选择排序算法{//选择排序(Selection Sort)是一种简单的排序算法,其实现原理如下://1、遍历待排序数组,从第一个元素开始。//2、假设当前遍历的元素为最小值,将其索引保存为最小值索引(minIndex)。//3、在剩余的未排序部分中,找到比当前最小值还要小的元素,并更新最小值索引。//4、在遍历结束后,将找到的最小值与当前遍历位置的元素进行交换。//5、重复步骤2到4,直到排序完成。//选择排序算法的时间复杂度为O(n^2),其中n是待排序数组的大小。尽管其时间复杂度较高,但选择排序算法比较简单易懂,并且在某些特定情况下,例如对于小规模的数组来说,其性能可能表现得比其他高级排序算法要好。public static void SelectionSortAlgorithmMain(){int[] array = { 64, 25, 12, 22, 11, 99, 3, 100 };Console.WriteLine("原始数组: ");PrintArray(array);SelectionSortAlgorithm(array);Console.WriteLine("排序后的数组: ");PrintArray(array);}static void SelectionSortAlgorithm(int[] arr){int n = arr.Length;for (int i = 0; i < n - 1; i++){// 在未排序部分中找到最小元素的索引int minIndex = i;for (int j = i + 1; j < n; j++){if (arr[j] < arr[minIndex]){minIndex = j;}}// 将最小元素与未排序部分的第一个元素交换位置int temp = arr[minIndex];arr[minIndex] = arr[i];arr[i] = temp;}}static void PrintArray(int[] arr){int n = arr.Length;for (int i = 0; i < n; ++i){Console.Write(arr[i] + " ");}Console.WriteLine();}}