码迷,mamicode.com
首页 > 编程语言 > 详细

冒泡排序

时间:2016-04-05 08:16:13      阅读:135      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!