氣泡排序正解

守望陽光01發表於2017-07-06

程式碼寫了試了一下氣泡排序的程式碼,發現網上大多數氣泡排序是由問題的,這裡我寫一下正解的氣泡排序。

這裡我把氣泡排序的方法封裝在一個類裡,以後想排序的時候直接呼叫就行了

 1  public void MaoPao(int[] list)
 2         {
 3             int temp;
 4             for (int i = 0; i < list.Length - 1; i++)
 5             {
 6                 for (int j = i + 1; j < list.Length; j++)
 7                 {
 8                     if (list[j] < list[i])
 9                     {
10                         temp = list[j];
11                         list[j] = list[i];
12                         list[i] = temp;
13                     }
14                 }
15             }
16         }
View Code

然後我們定義一個int陣列,現在我們來排序試試我們的氣泡排序有沒有用

這裡我遇到的問題有最後比較的資料轉換問題,首先是把每次比較的最小數賦給定義的int變數tem,然後是把最大數賦給j,最後是把tem賦給i,這是例子,你想輸出別的引數也可以,然後就是i初始值是0,j的初始值是i+1,我覺得最容易出錯的地方就是這兩個了。

 1  static void Main(string[] args)
 2         {
 3             int[] array = { 12, 13, 14, 69, 58, 78, 70, 85, 99, 23, 56, 42, 32 };
 4 
 5             Class1 class1 = new Class1();
 6             class1.MaoPao(array);
 7             for (int i = 0; i < array.Length; i++)
 8             {
 9                 Console.Write("第{0}個數是{1}\n", i + 1, array[i]);
10             }
11             Console.ReadKey();
12         }
View Code

相關文章