首页 > 学院 > 开发设计 > 正文

排序算法之选择排序

2019-11-17 02:47:43
字体:
来源:转载
供稿:网友
排序算法之选择排序

选择排序定义:每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。选择排序是不稳定的排序方法。

class PRogram{    static void Main(string[] args)    {        int[] array = new[] { 234, 632, 23, 643, 2, 6, -2, 423, 2342,43 };        Console.WriteLine("排序前:");        Console.WriteLine(string.Join(",", array));        SelectSort(array);        Console.WriteLine("排序后:");        Console.WriteLine(string.Join(",", array));        Console.ReadKey();    }        /// <summary>    /// 选择排序    /// </summary>    /// <param name="sources">目标数组</param>    private static void SelectSort(int[] sources)    {        for (int i = 0, len = sources.Length - 1; i <= len; i++)        {            // 假设最小值索引            int minIndex = i;            // 循环遍历一遍找到最小值的索引            for (int j = i + 1; j <= len; j++)            {                // 如果最小值比其他元素大,重新设置最小值的索引                if (sources[minIndex] > sources[j])                {                    minIndex = j;                }            }            // 临时变量交换最小值的位置;            int temp = sources[i];            sources[i] = sources[minIndex];            sources[minIndex] = temp;        }    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表