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是待排序数组的大小。尽管其时间复杂度较高,但选择排序算法比较简单易懂,并且在某些特定情况下,例如对于小规模的数组来说,其性能可能表现得比其他高级排序算法要好。

相关推荐
hez20104 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
聚客AI12 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v15 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工17 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
mudtools17 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
骑自行车的码农18 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了18 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo19 小时前
322:零钱兑换(三种方法)
算法
唐青枫21 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
NAGNIP2 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法