(3)C#for迴圈實現氣泡排序
阿新 • • 發佈:2019-02-04
class Program { static void Main(string[] args) { int[] a = { 15,17,3,4,4,19,6,7,11,9,10}; ////氣泡排序:從第一個數開始,相鄰兩個數進行比較,大的靠前,小的靠後,直到比較完一輪,最小的數放在最後。第二輪開始,比較到a.lenght-1-1,最小的數放在最後面...一直重複。 ////比較完一輪,發現只是選到了最小的數到下面,那麼還要比第二輪,就相當for巢狀。 for (int j = 0; j < a.Length-1;j++ ) { for (int i = 0; i < a.Length - 1 - j;i++ ) { int temp; if (a[i] < a[i + 1]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } //選擇排序,選定最大/最小的數放在首位置, //例子:第一輪 :19,15,3,4,4,17,6,7,11,9,10 //第二輪:19,17,3,4,4,15,6,7,11,9,10 //從a[0]比較到a[10] //19,17,15,4,4,3,6,7,11,9,10 //19,17,15,4,4,3,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //19,17,3,4,4,15,6,7,11,9,10 //從上面可以看出第二輪從第2個數開始比較, for(int i = 0 ;i<a.Length-1;i++) { for (int j = i+1; j < a.Length; j++) { int temp; //如果原數比被比較的數小,則交換。原數就可以取到第一個大的整數(被比較的陣列的元素) if (a[i] < a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } foreach( int inta in a) { Console.WriteLine(inta); } Console.ReadLine(); } }