冒泡排序
1 int temp; 2 int[] arrSort = new int[] { 10, 8, 3, 5, 6, 7, 9 }; 3 for (int i = 0; i < arrSort.Length; i++) 4 { 5 for (int j = i + 1; j < arrSort.Length; j++) 6 { 7 if (arrSort[j] < arrSort[i]) 8 { 9 temp = arrSort[j]; 10 arrSort[j] = arrSort[i]; 11 arrSort[i] = temp; 12 } 13 } 14 }
另一種排序方法(不符合冒泡排序的原理)
1 int i, j, temp; 2 int[] arrSort = new int[] { 10, 8, 3, 5, 6, 7, 9 }; 3 for (j = 0; j < arrSort.Length; j++) 4 { 5 for (i = 0; i < arrSort.Length - 1; i++) 6 { 7 if (arrSort[i] > arrSort[i + 1]) 8 { 9 temp = arrSort[i]; 10 arrSort[i] = arrSort[i + 1]; 11 arrSort[i + 1] = temp; 12 } 13 14 count++; 15 } 16 }
如果用一個變量記錄內循環 循環次數 就會發現第二種排序方法 循環次數高於冒泡排序