美文网首页
冒泡排序优化

冒泡排序优化

作者: keloid | 来源:发表于2018-12-02 19:48 被阅读4次

    冒泡排序:是一种交换排序,其基本思想是两两比较相邻记录的关键字,如果反序则交换,直到没有反序的记录为止。

    为了避免序列已有序的情况下还进行比较,可以设置一个标记变量来减少循环。

    C#示例代码如下:

    using System;
    using System.Linq;
    
    namespace ConsoleApp1
    {
    
        class Program
        {
            static void Main(string[] args)
            {
                int[] sqList = new int[] {2,1,3,4 };
                BubbleSort(sqList);
                sqList.ToList().ForEach(s => Console.Write(s+" "));
                Console.ReadLine(); 
            }
    
            static void BubbleSort(int[] sqList)
            {
                bool status = true;
                for (int i = 0; i < sqList.Length && status; i++)
                {
                   status = false;
                    for (int j = sqList.Length - 2; j >= i; j--)
                    {
                        if (sqList[j] > sqList[j + 1])
                        {
                            Swap(sqList, j, j + 1);
                            status = true;
                        }
                    }
                }
            }
    
            static void Swap(int[] sqList, int index1, int index2)
            {
                int value1 = sqList[index1];
                sqList[index1] = sqList[index2];
                sqList[index2] = value1;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:冒泡排序优化

          本文链接:https://www.haomeiwen.com/subject/iklscqtx.html