|
当编写程序时,了解和使用不同的算法对解决问题至关重要。以下是C#中常用的10种算法,每个算法都伴随着示例代码和详细说明。
1. 冒泡排序 (Bubble Sort):
冒泡排序是一种简单的比较排序算法,它多次遍历数组,将较大的元素逐渐浮动到数组的末尾。- public static void BubbleSort(int[] arr)
- {
- int n = arr.Length;
- for (int i = 0; i < n - 1; i++)
- {
- for (int j = 0; j < n - i - 1; j++)
- {
- if (arr[j] > arr[j + 1])
- {
- int temp = arr[j];
- arr[j] = arr[j + 1];
- arr[j + 1] = temp;
- }
- }
- }
- }
复制代码 2. 快速排序 (Quick Sort):
快速排序是一种高效的分治排序算法,它通过选择一个基准元素并将数组分为较小和较大的两部分来进行排序。- public static void QuickSort(int[] arr, int low, int high)
- {
- if (low < high)
- {
- int partitionIndex = Partition(arr, low, high);
- QuickSort(arr, low, partitionIndex - 1);
- QuickSort(arr, partitionIndex + 1, high);
- }
- }
- public static int Partition(int[] arr, int low, int high)
- {
- int pivot = arr[high];
- int i = low - 1;
- for (int j = low; j < high; j++)
- {
- if (arr[j] < pivot)
- {
- i++;
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
- int swap = arr[i + 1];
- arr[i + 1] = arr[high];
- arr[high] = swap;
- return i + 1;
- }
复制代码 3. 合并排序 (Merge Sort):
合并排序是一种稳定的分治排序算法,它将数组分成两半,分别排序后再合并。- public static void MergeSort(int[] arr)
- {
- int n = arr.Length;
- if (n > 1)
- {
- int mid = n / 2;
- int[] left = new int[mid];
- int[] right = new int[n - mid];
- for (int i = 0; i < mid; i++)
- left[i] = arr[i];
- for (int i = mid; i < n; i++)
- right[i - mid] = arr[i];
- MergeSort(left);
- MergeSort(right);
- int i = 0, j = 0, k = 0;
- while (i < mid && j < (n - mid))
- {
- if (left[i] < right[j])
- arr[k++] = left[i++];
- else
- arr[k++] = right[j++];
- }
- while (i < mid)
- arr[k++] = left[i++];
- while (j < (n - mid))
- arr[k++] = right[j++];
- }
- }
复制代码 4. 二分查找 (Binary Search):
二分查找是一种高效的查找算法,它要求在有序数组中查找特定元素。
[code]public static int BinarySearch(int[] arr, int target){ int low = 0, high = arr.Length - 1; while (low |
|