注:int[] 数组为引用类型
1 namespace demo 2 { 3 public class Program 4 { 5 static void Main(string[] args) 6 { 7 //原数组 8 int[] nums = new int[] { 12, 10, 4, 8, 1, 3, 2, 9, 5, 6, 18 }; 9 Console.Write("原数组:"); 10 foreach (int n in nums) 11 Console.Write($"{n} "); 12 13 //升序 14 BubbleSortAsc(nums); 15 Console.Write("\n小->大:"); 16 foreach (int n in nums) 17 Console.Write($"{n} "); 18 19 //降序 20 BubbleSortDesc(nums); 21 Console.Write("\n大->小:"); 22 foreach (int n in nums) 23 Console.Write($"{n} "); 24 Console.ReadKey(); 25 } 26 /// <summary> 27 /// 从小到大排序(使用中间变量) 28 /// </summary> 29 static void BubbleSortAsc(int[] nums) 30 { 31 int tmp; 32 for(int i=0;i<nums.Length;i++) 33 { 34 for(int j=i+1;j<nums.Length;j++) 35 { 36 if(nums[j]<nums[i]) 37 { 38 tmp = nums[i]; 39 nums[i] = nums[j]; 40 nums[j] = tmp; 41 } 42 } 43 } 44 } 45 /// <summary> 46 /// 从大到小排序 47 /// </summary> 48 static void BubbleSortDesc(int[] nums) 49 { 50 for(int i=0;i<nums.Length;i++) 51 { 52 for(int j=i+1;j<nums.Length;j++) 53 { 54 if(nums[i]<nums[j]) 55 { 56 nums[i] = nums[i] + nums[j]; 57 nums[j] = nums[i] - nums[j]; 58 nums[i] = nums[i] - nums[j]; 59 } 60 } 61 } 62 } 63 } 64 }
执行结果: