C#實現簡單的冒泡排序

1、C#代碼下:

using System;

namespace ConsoleApplication1

{

    class Program

    {

        static void Main()

        {

            int[] arrSort = new int[] { 10, 8, 3, 5, 6, 7, 9 };//初始化排序數據

            Bubble_Sort(ref arrSort);//調用冒泡排序方法


            for (int i = 0; i < arrSort.Length; i++)//輸出排序結果

            {

                Console.WriteLine("排序的結果爲:{0}", arrSort[i]);

            }

            Console.ReadLine();//暫停輸出窗口

        }

        /// <summary>

        /// C#實現簡單的冒泡排序

        /// </summary>

        private static void Bubble_Sort(ref int[] arrSort)//ref表示引用型

        {

            int temp;//預先定義一箇中間變量

            for (int i = 0; i < arrSort.Length; i++)

            {

                for (int j = i + 1; j < arrSort.Length; j++)

                {

                    if (arrSort[j] < arrSort[i])//交換數據位置

                    {

                        temp = arrSort[j];

                        arrSort[j] = arrSort[i];

                        arrSort[i] = temp;

                    }

                }

            }

        }

    }

}


2、輸出的結果如下:

image.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章