QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 925|回复: 0

[C#/.NET] C#选择排序(Selection Sort)算法

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1322 小时
   最后登录 : 2025-9-15

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2023-7-22 01:42:18 | 显示全部楼层 |阅读模式
选择排序(Selection Sort)原理介绍4 n3 n( P' |" J" T' Y" s7 A
选择排序(Selection Sort)是一种简单的排序算法,其实现原理如下:
# O2 H) W0 }9 s2 a& s8 q遍历待排序数组,从第一个元素开始。
0 M6 G  a& t: J0 W) y9 I% X8 B假设当前遍历的元素为最小值,将其索引保存为最小值索引(minIndex)。6 k- n/ l" U: {5 ?# O" ]
在剩余的未排序部分中,找到比当前最小值还要小的元素,并更新最小值索引。
0 O' }' g1 T, R+ M在遍历结束后,将找到的最小值与当前遍历位置的元素进行交换。/ A6 Z' p2 l* N& F! r* e
重复步骤2至4,直到排序完成。
' o8 e7 Y9 {+ Z" ^$ e; [/ N, v8 J& VC#代码实现
) z8 ]2 w( Q# ]: j
/// <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();
        }
1.jpg ( S& R1 t0 {! d" b
总结. C' n+ g3 `# u( r" r) o7 F
选择排序算法的时间复杂度为O(n^2),其中n是待排序数组的大小。尽管其时间复杂度较高,但选择排序算法比较简单易懂,并且在某些特定情况下,例如对于小规模的数组来说,其性能可能表现得比其他高级排序算法要好。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2025-9-17 08:54

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表