冒泡排序(java,c#)

---------------------------------------------------------------------------------------JAVA---------------------------------------------------------------------------------

public static void main(String[] args) {

int[] scores = new int[5];         //成績數組
         int i, j;                          //循環變量
         int x;                             //臨時變量
         Scanner input = new Scanner(System.in);
         //從控制檯接收成績
         System.out.println("請輸入5個學生的成績:");
         for (i = 0; i < 5; i++ )
         {
        System.out.println("請輸入第" + (i+1) + "個學生的成績:");
             scores[i] = input.nextInt();
         }
         //冒泡排序現在正式開始
         //外層循環控制比較多少輪
         for(i = 0; i < scores.length - 1; i++)
         {
             //內層循環:將最大的數交換到最後
             for(j = 0; j < scores.length-1-i; j++)
             {
                 if(scores[j] > scores[j+1])
                 {
                     //交換元素
                     x = scores[j];
                     scores[j] = scores[j+1];
                     scores[j+1] = x;
                 }
             }
         }
         //排序後輸出
         System.out.println("排序後的成績爲:");
         for(i = 0; i<scores.length;i++)
         {
        System.out.println(scores[i]);
         }
}


---------------------------------------------------------------------------------------C#---------------------------------------------------------------------------------

static void Main(string[] args)
        {
            int[] scores = new int[5];         //成績數組
            int i, j;                          //循環變量
            int x;                             //臨時變量
            //從控制檯接收成績
            Console.WriteLine("請輸入5個學生的成績:");
            for (i = 0; i < 5; i++ )
            {
                Console.WriteLine("請輸入第{0}個學生的成績:",i+1);
                scores[i] = int.Parse(Console.ReadLine());
            }
            //冒泡排序現在正式開始
            //外層循環控制比較多少輪
            for(i = 0; i < scores.Length - 1;i++)
            {
                //內層循環:將最大的數交換到最後
                for(j = 0;j < scores.Length-1-i;j++)
                {
                    if(scores[j] > scores[j+1])
                    {
                        //交換元素
                        x = scores[j];
                        scores[j] = scores[j+1];
                        scores[j+1] = x;
                    }
                }
            }
            //排序後輸出
                    Console.WriteLine("排序後的成績爲:");
                    for(i = 0; i<scores.Length;i++)
                    {
                        Console.WriteLine("{0}",scores[i]);
                    }


            Console.ReadLine();
        }
    }

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