C# 冒泡排序

来源:互联网 发布:mongodb 默认端口 编辑:程序博客网 时间:2024/05/29 04:45

冒泡排序的基本原理是:下沉上浮。

如果是从大到小排序就是上浮,如果是从小到大排序就是下沉。

这种排序需要两个循环控制,一个是控制循环的次数一个是控制数据的比较。

如果有N个数需要进行排序,那么需要轮回N-1次。每一次的比较次数是数组的长度减去1再减去已经比较过的循环次数。

语言描述不能够准确的表述其意,还是看具体的代码分析比较好。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] std = new int[5];
            //输入要比较的数据
            for (int i = 0; i < 5; i++)
            {
                std[i] = Convert.ToInt32(Console.ReadLine());
            }
            //控制循环的次数
            for (int i = 0; i <= std.Length-1; i++)
            {
                //控制比较的次数,
                for (int j = 0; j < std.Length - i-1; j++)
                {//进行数据的交换
                    if (std[j] > std[j + 1])
                    {
                        int temp;
                        temp = std[j];
                        std[j] = std[j + 1];
                        std[j + 1] = temp;
                    }
                }
            }
            //输出比较过后的数据
            for (int i = 0; i < std.Length; i++)
            {
                Console.WriteLine(std[i]);
            }


            Console.ReadKey();
        }
    }
}

0 0
原创粉丝点击