[C#] 氣泡排序法 (Bubble Sort)

  • 33339
  • 0

[C#] 氣泡排序法 (Bubble Sort)

Introduction

基本原理就是把每兩個鄰近的物件作比較,大小次序不對時就互換。每次比完一輪(一回)後最大值就會被移到最右邊。

比方說 List 中有 N 個元素。

所以必須比較 n - 1 回。每回比較 n - i 次。

當有一輪,沒有任何交換的動作發生時,代表排序已完成。

 

Examples

 


   public static void bubbleSort(int[] list) {
            int n = list.Length;
            int temp;
            int Flag = 1; //旗標
            int i;
            for (i = 1; i <= n - 1 && Flag == 1; i++) {    // 外層迴圈控制比較回數
                Flag = 0;
                for (int j = 1; j <= n - i; j++) {  // 內層迴圈控制每回比較次數            
                    if (list[j] < list[j - 1]) {  // 比較鄰近兩個物件,右邊比左邊小時就互換。	       
                        temp = list[j];
                        list[j] = list[j - 1];
                        list[j - 1] = temp;
                        Flag = 1;
                    } 	
                }             
            }   
        } 

        static void Main(string[] args) {
            int[] list = new int[6] { 3, 4, 6, 8, 9, 7 };
            Console.WriteLine("Before sort");
            for (int n = 0; n < list.Length; n++)
                Console.Write(list[n] + " ");
            bubbleSort(list);
            Console.WriteLine("\nAfter sort");
            for (int n = 0; n < list.Length; n++)
                Console.Write(list[n] + " ");

            Console.ReadKey();
        }

 

Refrence

http://en.wikipedia.org/wiki/Bubble_sort

三小俠  小弟獻醜,歡迎指教