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

排序算法之冒泡排序

2019-11-17 02:47:46
字体:
来源:转载
供稿:网友
排序算法之冒泡排序

冒泡排序算法原理:

1、比较相邻的元素。如果第一个比第二个大,就交换他们两个。

2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。

3、针对所有的元素重复以上的步骤,除了最后一个。

4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

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));        BubbleSort(array);        Console.WriteLine("排序后:");        Console.WriteLine(string.Join(",", array));        Console.ReadKey();    }    /// <summary>    /// 冒泡排序    /// </summary>    /// <param name="sources">目标数组</param>    private static void BubbleSort(int[] sources)    {        int i, j, temp;        for (i = 0; i < sources.Length - 1; i++)        {            // 与后面的元素比较            for (j = 0; j < sources.Length - 1 - i; j++)            {                if (sources[j] > sources[j + 1]) // > 升序,< 降序                {                    // 交换元素                    temp = sources[j];                    sources[j] = sources[j + 1];                    sources[j + 1] = temp;                }            }        }    }}


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