数组的定义方式:
int[] Scores={1,2,3,4,5};//方式1 int[] Scores=[5]{1,2,3,4,5};//方式2 int[] Scores1=new int[5];//0向量,5个0 Console.WriteLine(Scores[0]); foreach(int score in Scores){//遍历数组,foreach语句 Console.WriteLine(score); }
数组从小到大排序:Array.Sort(数组);
public static void Main(string[] args) { Console.WriteLine("请输入一组数据,以空格分隔:"); string str = Console.ReadLine();//回车后,才执行以下代码 string[] strArray = str.Split(' ');//字符串按空格拆分成数组 int[] nums = new int[strArray.Length];//等长度0数组 for (int i = 0; i < strArray.Length; i++) {//替换思维 nums[i] = Convert.ToInt32(strArray[i]); } Array.Sort(nums);//从小到大排序,nums被改变 foreach (int num in nums) { Console.Write(num + " "); } Console.ReadKey(); }
冒泡排序
int[] scores = { 89, 90, 98, 56, 60, 91, 93, 85 }; Console.WriteLine("排序前:"); foreach(int score in scores) { Console.Write(score + " "); } Console.WriteLine(); Console.ReadKey(); int temp; for (int i = 0; i < scores.Length - 1; i++) { for(int j = i + 1; j < scores.Length; j++) { if (scores[i] < scores[j]) { temp=scores[i]; scores[i] = scores[j]; scores[j] = temp; } } } Console.WriteLine("从大到小排序:"); foreach (int score in scores) { Console.Write(score + " "); } Console.ReadKey();