冒泡排序口诀:
升序(从小到大):
两for一if;
大于连;
相 交换;
再来个for遍历;
外层N-1;
内层N-1-i;
说再多不如上代码,更明显:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int[] array = {1, 3, 5, 7, 90, 2, 4, 6, 8, 10}; 6 array= GetSort(array); 7 for (int i = 0; i < array.Length; i++) 8 { 9 Console.Write(array[i] + " "); 10 } 11 Console.ReadKey(); 12 } 13 /// <summary> 14 /// 冒泡排序 15 /// </summary> 16 /// <param name="array"></param> 17 /// <returns></returns> 18 private static int[] GetSort(int[] array) 19 { 20 //外层循环n-1 21 for (int i = 0; i < array.Length-1; i++) 22 { 23 //内层循环n-1-i 24 for (int j = 0; j < array.Length-1-i; j++) 25 { 26 if (array[j] > array[j+ 1]) 27 { 28 int temp = array[j]; 29 array[j] = array[j + 1]; 30 array[j + 1] = temp; 31 } 32 } 33 } 34 return array.ToArray(); 35 } 36 }