首页 > 编程语言 > 详细

冒泡排序

时间:2016-04-05 08:13:45      阅读:285      评论:0      收藏:0      [点我收藏+]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace csharpsTest
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] arr = { 5, 2, 3, 6 };

            Program mProgram = new Program();

            mProgram.BubbleSort(arr);

            for (int i = 0; i < arr.Length; ++i)
            {
                System.Console.Write(" " + arr[i]);
            }
        }

        void BubbleSort(int[] arr)
        {
            int length = arr.Length;

            int testTimes = 0;

            for (int i = length - 1; i > 0; --i)
            {
                bool isAlready = true;
                for (int j = 1; j <= i; ++j)
                {
                    if (arr[j - 1] > arr[j])
                    {
                        Swap(ref arr[j - 1], ref arr[j]);
                        isAlready = false;
                    }
                }
                testTimes++;
                if (isAlready)
                {
                    break;
                }
            }
            System.Console.WriteLine("testTims:" + testTimes);
        }

        void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
    }
}

  

冒泡排序

原文:http://www.cnblogs.com/sun-shadow/p/5353672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!