冒泡排序原理:(升序)通過當前位置數和後一個位置數進行比較 如果當前數比後一個數大 則交換位置, 完成後 比較基數的位置變成下一個數。直到數組末尾,當程式運行完第一遍 最大的數已經排序到最後一個位置了。次數可以減少迴圈數不用管最後一個數 降序排序同理 不過是把比較方式變成判斷當前數是否小於下一個數 ...
冒泡排序原理:(升序)通過當前位置數和後一個位置數進行比較 如果當前數比後一個數大 則交換位置, 完成後 比較基數的位置變成下一個數。直到數組末尾,當程式運行完第一遍 最大的數已經排序到最後一個位置了。次數可以減少迴圈數不用管最後一個數
降序排序同理 不過是把比較方式變成判斷當前數是否小於下一個數 如果小於則交換
下麵直接上代碼
雙重迴圈方式:
1 using System; 2 using System.Collections.Generic; 3 4 namespace TestConsole 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 //創建一個亂序數組 11 List<int> ints = new List<int> { 1, 2, 3, 4, 8, 6, 4, 1, 0, 5, 5, 0, 5, 1, 16, 1, 32, 1, 54, 68, 4, 21, 56, 14, 856, 48, 6, 12, 3, 5 }; 12 13 //獲取數組長度 14 int count = ints.Count; 15 16 //外圈迴圈 數組有多少個數就迴圈多少次 每完成一次內部迴圈減少一次外部迴圈(最後一個數以經是最大 不用參與比較了) 17 for (int i = count; i > 0; i--) 18 { 19 //內部迴圈 比較當前位置數和下一個位置的數大小 20 for (int j = 0; j < i; j++) 21 { 22 //判斷是否到數組尾 23 if (j + 1 == i) continue; 24 //判斷當前數是否比下一個數大 25 if (ints[j] > ints[j + 1]) 26 { 27 //把當前數替換到臨時變數 28 var t = ints[j]; 29 //把下一個數替換到當前位置 30 ints[j] = ints[j + 1]; 31 //把臨時變數替換到下一個數的位置 32 ints[j + 1] = t; 33 } 34 } 35 //減少外圈迴圈 36 count--; 37 } 38 Console.WriteLine(string.Join(",", ints)/*string.Join("分隔符",對象數組) 用於把數組元素分割成字元串*/ ); 39 Console.ReadKey(); 40 } 41 } 42 }
while實現方式:
1 using System; 2 using System.Collections.Generic; 3 4 namespace TestConsole 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 //創建一個亂序數組 11 List<int> ints = new List<int> { 1, 2, 3, 4, 8, 6, 4, 1, 0, 5, 5, 0, 5, 1, 16, 1, 32, 1, 54, 68, 4, 21, 56, 14, 856, 48, 6, 12, 3, 5 }; 12 13 //獲取數組長度 14 int count = ints.Count; 15 16 //外圈迴圈 數組有多少個數就迴圈多少次 每完成一次內部迴圈減少一次外部迴圈(最後一個數以經是最大 不用參與比較了) 17 while (count > 0) 18 { 19 //內部迴圈 比較當前位置數和下一個位置的數大小 20 for (int j = 0; j < count; j++) 21 { 22 //判斷是否到數組尾 23 if (j + 1 == count) continue; 24 //判斷當前數是否比下一個數大 25 if (ints[j] > ints[j + 1]) 26 { 27 //把當前數替換到臨時變數 28 var t = ints[j]; 29 //把下一個數替換到當前位置 30 ints[j] = ints[j + 1]; 31 //把臨時變數替換到下一個數的位置 32 ints[j + 1] = t; 33 } 34 } 35 //減少外圈迴圈 36 count--; 37 } 38 Console.WriteLine(string.Join(",", ints)/*string.Join("分隔符",對象數組) 用於把數組元素分割成字元串*/ ); 39 Console.ReadKey(); 40 } 41 } 42 }
純屬個人理解,如果偏差請各位大佬指正~~~~