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

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

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

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

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

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

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

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

C#代码实现

复制代码
        /// <summary>
        /// 选择排序算法
        /// </summary>
        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();
        }

总结

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

相关推荐
倦王22 分钟前
力扣日刷251120
算法·leetcode·职场和发展
F_D_Z24 分钟前
【k近邻】Kd树构造与最近邻搜索示例
算法·机器学习·近邻算法·k近邻算法
断剑zou天涯35 分钟前
【算法笔记】从暴力递归到动态规划(二)
java·算法·动态规划
RTC老炮37 分钟前
webrtc降噪-SpeechProbabilityEstimator类源码分析与算法原理
算法·webrtc
ThreePointsHeat42 分钟前
Unity 关于打包WebGL + jslib录制RenderTexture画面
unity·c#·webgl
WWZZ20251 小时前
快速上手大模型:深度学习9(池化层、卷积神经网络1)
人工智能·深度学习·神经网络·算法·机器人·大模型·具身智能
Boop_wu1 小时前
[Java EE] 多线程编程初阶
java·jvm·算法
a***97681 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
cpp_25012 小时前
P1765 手机
数据结构·c++·算法·题解·洛谷
未到结局,焉知生死2 小时前
PAT每日三题11-20
c++·算法