• C#选择排序(Selection Sort)算法


    选择排序(Selection Sort)原理介绍

    选择排序(Selection Sort)是一种简单的排序算法,其实现原理如下:

    1. 遍历待排序数组,从第一个元素开始。

    2. 假设当前遍历的元素为最小值,将其索引保存为最小值索引(minIndex)。

    3. 在剩余的未排序部分中,找到比当前最小值还要小的元素,并更新最小值索引。

    4. 在遍历结束后,将找到的最小值与当前遍历位置的元素进行交换。

    5. 重复步骤2至4,直到排序完成。

    C#代码实现

    1.         /// <summary>
    2.         /// 选择排序算法
    3.         /// </summary>
    4.         public static void SelectionSortAlgorithmMain()
    5.         {
    6.             int[] array = { 6425122211993100 };
    7.             Console.WriteLine("原始数组: ");
    8.             PrintArray(array);
    9.             SelectionSortAlgorithm(array);
    10.             Console.WriteLine("排序后的数组: ");
    11.             PrintArray(array);
    12.         }
    13.         static void SelectionSortAlgorithm(int[] arr)
    14.         {
    15.             int n = arr.Length;
    16.             for (int i = 0; i < n - 1; i++)
    17.             {
    18.                 // 在未排序部分中找到最小元素的索引
    19.                 int minIndex = i;
    20.                 for (int j = i + 1; j < n; j++)
    21.                 {
    22.                     if (arr[j] < arr[minIndex])
    23.                     {
    24.                         minIndex = j;
    25.                     }
    26.                 }
    27.                 // 将最小元素与未排序部分的第一个元素交换位置
    28.                 int temp = arr[minIndex];
    29.                 arr[minIndex] = arr[i];
    30.                 arr[i] = temp;
    31.             }
    32.         }
    33.         static void PrintArray(int[] arr)
    34.         {
    35.             int n = arr.Length;
    36.             for (int i = 0; i < n; ++i)
    37.             {
    38.                 Console.Write(arr[i] + " ");
    39.             }
    40.             Console.WriteLine();
    41.         }

    图片

    总结

    选择排序算法的时间复杂度为O(n^2),其中n是待排序数组的大小。尽管其时间复杂度较高,但选择排序算法比较简单易懂,并且在某些特定情况下,例如对于小规模的数组来说,其性能可能表现得比其他高级排序算法要好。

  • 相关阅读:
    [OtterCTF 2018] 电子取证
    Java实现Excel批量导入数据库
    如何在已有的vue项目里面使用electron? (普通项目转成桌面端应用)
    SSRF
    C++prime读书笔记(二)C++标准库
    Ubuntu系统配置DDNS-GO【笔记】
    Spring Cloud【为什么需要监控系统、Prometheus环境搭建、Grafana环境搭建 、微服务应用接入监控 】(十七)
    智慧机场航线监测系统:提升航空运输安全与效率的新一步
    第三章 非常高的水平层
    一条Select语句在MySQL-Server层的执行过程
  • 原文地址:https://blog.csdn.net/qq_37237487/article/details/133936060