今天练习了冒泡算法,能运行可不能实现。搞了好久,学习了 ref 的作用,在一个方法A中调用方法B,你想给A方法中的变量通过方法B来获取值,这时就要用到ref关键字了。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 冒泡排序法 { class Program { static void Main(string[] args) { int[] arr1 = new int[] { 3, 5, 4, 19, 28, 17, 12, 18, 7 }; int length = arr1.Length; maopao (arr1,length); foreach(int i in arr1) { Console.Write(i+" "); } Console.Read(); } static void change(ref int left,ref int right) { if (left < right) { return; } else { int temp; temp = left; left = right; right = temp; } } static void maopao(int[] arr,int length) { for(int i=0;i<length-1;i++) { for(int j=0;j<length-1;j++) { change(ref arr[j],ref arr[j+1]); } } } } }