2015年11月9日 星期一

C7_3 冒泡排序

public class BubbleSor
{
    public int Swap(int x, int y)
    {
        int temp;
        temp = x;
        x = y;
        y = temp;
        return temp;
    }
    public void Sort(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 = this.Swap(arr[j + 1], arr[j]);
                    exchange = true; //發生了交換,故將交換標誌置為真
                }
            }
            if (!exchange) //本次排序未發生交換,提前終止演算法
            {
                break;
            }
        }

    }
}

沒有留言: