以下是使用C#实现选择排序算法的示例代码:
- using System;
-
- class SelectionSort
- {
- static void Main(string[] args)
- {
- int[] arr = { 64, 25, 12, 22, 11 };
-
- Console.WriteLine("排序前:");
- PrintArray(arr);
-
- SelectionSortAlgorithm(arr);
-
- Console.WriteLine("\n排序后:");
- PrintArray(arr);
- }
-
- static void SelectionSortAlgorithm(int[] arr)
- {
- int n = arr.Length;
- for (int i = 0; i < n - 1; i++)
- {
- int min_index = i;
- for (int j = i + 1; j < n; j++)
- {
- if (arr[j] < arr[min_index])
- {
- min_index = j;
- }
- }
- // 将最小元素与未排序部分的第一个元素交换位置
- int temp = arr[min_index];
- arr[min_index] = arr[i];
- arr[i] = temp;
- }
- }
-
- static void PrintArray(int[] arr)
- {
- foreach (int num in arr)
- {
- Console.Write(num + " ");
- }
- Console.WriteLine();
- }
- }
这段代码定义了一个名为 SelectionSort 的类,其中包含了一个静态方法 SelectionSortAlgorithm 用于实现选择排序算法。在主程序中,我们创建一个整数数组,然后调用 SelectionSortAlgorithm 方法对其进行排序,并打印排序前后的数组。
