冒泡排序原理:(升序)通過當前位置數和后一個位置數進行比較 如果當前數比后一個數大 則交換位置, 完成后 比較基數的位置變成下一個數,直到陣列末尾,當程式運行完第一遍 最大的數已經排序到最后一個位置了,次數可以減少回圈數不用管最后一個數
降序排序同理 不過是把比較方式變成判斷當前數是否小于下一個數 如果小于則交換
下面直接上代碼
雙重回圈方式:
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 }
純屬個人理解,如果偏差請各位大佬指正~~~~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/67565.html
標籤:其他
上一篇:3個渲染路徑
下一篇:關于Socket檔案傳輸
