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

相关推荐
白兰地空瓶5 分钟前
你以为树只是画图?不——它是算法面试的“隐形主角”
前端·javascript·算法
好易学·数据结构14 分钟前
可视化图解算法74:最小花费爬楼梯
数据结构·算法·leetcode·动态规划·力扣
Maỿbe40 分钟前
力扣hot图论部分
算法·leetcode·图论
LYFlied1 小时前
【每日算法】LeetCode 78. 子集
数据结构·算法·leetcode·面试·职场和发展
月明长歌1 小时前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
子枫秋月1 小时前
C++字符串操作与迭代器解析
数据结构·算法
鹿角片ljp1 小时前
力扣234.回文链表-反转后半链表
算法·leetcode·链表
(●—●)橘子……1 小时前
记力扣1471.数组中的k个最强值 练习理解
数据结构·python·学习·算法·leetcode
oioihoii1 小时前
C++共享内存小白入门指南
java·c++·算法
Bruce_kaizy1 小时前
c++图论————图的基本与遍历
c++·算法·图论