2015年11月6日 星期五

C5_7 泡沫排序演算法

using System;
namespace C5_7
{
    public class BSort
    {
        public static void BubbleSot(int[] arr)
        {
            int i, j, temp;
            bool exchange; //交換標誌
            for (i = 0; i < arr.Length; i++) //最多做arr.Length 1趟排序
            {
                exchange = false; //本趟排序開始前,交換標誌為假
                for (j = arr.Length - 2; j >= i; j--)
                {
                    if (arr[j + 1] < arr[j])
                    {
                        //開始交換
                        temp = arr[j + 1];
                        arr[j + 1] = arr[j];
                        arr[j] = temp;
                        exchange = true; //發生了交換,將交換標誌設為真
                    }
                }
                if (!exchange) //本趟排序未發生交換,提前終止演算法
                {
                    break;
                }
            }

        }
        public static void Main()
        {
            int[] arr = { 1,1,3,4,5,9,5,11};
            string array = "";
            for (int i = 0; i < arr.Length-1; i++)
            {
                array += arr[i] + " ";
            }
            array += arr[arr.Length - 1];
            Console.WriteLine("用泡沫演算法對資料({0})進行排序如下:", array);
            BubbleSot(arr);
            for (int j = 0; j < arr.Length; j++)
            {
                Console.Write("{0} ", arr[j]);
            }
        }
    }
}

沒有留言: