C#冒泡排序,最完美,最简洁的两种方式
1 var array = new int[] { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 }; 2 int temp; 3 //排序方法1 4 for (int i = 0; i < array.Length - 1; i++) 5 { 6 for (int j = 0; j < array.Length - i - 1; j++) 7 { 8 if (array[j] > array[j + 1]) 9 { 10 temp = array[j]; 11 array[j] = array[j + 1]; 12 array[j + 1] = temp; 13 } 14 } 15 } 16 foreach (var item in array) 17 { 18 Console.WriteLine(item); 19 } 20 Console.ReadKey(); 21 //排序2: 22 array = new int[] { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 }; 23 for (int i = 0; i < array.Length - 1; i++) 24 { 25 for (int j = i + 1; j < array.Length; j++) 26 { 27 if (array[j] < array[i]) 28 { 29 temp = array[i]; 30 array[i] = array[j]; 31 array[j] = temp; 32 } 33 } 34 } 35 foreach (var item in array) 36 { 37 Console.WriteLine(item); 38 } 39 Console.ReadKey();