Bubble Sort

#C#

Posted by Phyxsius on 2023-09-24


internal class Program
{
    private static void Main(string[] args)
    {
        int[] ary = new int[5];    //宣告陣列大小為5

        Random rnd = new Random();  //產生亂數初始值

        for (int i=0; i<ary.Length; i++)
        {
            ary[i] = rnd.Next(1, 10);   //亂數產生,亂數產生的範圍是1~9
        }

        Console.WriteLine("原始陣列內容:");
        showArray(ary);

        BubbleSort(ary);

        Console.WriteLine("由小到大排序後陣列內容:");
        showArray(ary);
    }

    static void BubbleSort(int[] ary)
    {
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();  //計算程式時間開始

        int counter = 0;

        for (int i = 0; i < ary.Length; i++)
        {
            for (int j = 0; j < ary.Length-1; j++)
            {
                if (ary[j] > ary[j+1])
                {
                    swap(ary, j, j+1);
                }
                counter++;
            }
            Console.Write($"第{i+1}輪結果:");
            showArray(ary);
        }
        Console.WriteLine("執行次數:" + counter);

        stopWatch.Stop();   //計算程式時間結束
        Console.WriteLine("程式執行時間(秒):" + (stopWatch.Elapsed.TotalMilliseconds/1000));
    }

    //兩個值互相交換
    static void swap(int[] ary, int value1, int value2)
    {
        int tmp = ary[value2];
        ary[value2] = ary[value1];
        ary[value1] = tmp;
    }

    //顯示陣列內容
    static void showArray(int[] ary)
    {
        for (int i=0; i<ary.Length; i++)
        {
            Console.Write(ary[i] + ",");
        }
        Console.WriteLine();
    }
}

#C#







Related Posts

【瀏覽器資料存取】cookies、localStorage、sessionStorage

【瀏覽器資料存取】cookies、localStorage、sessionStorage

Apple ios Enterprise Distribution App implement

Apple ios Enterprise Distribution App implement

Node.js 和Node.js REPL 關係

Node.js 和Node.js REPL 關係


Comments