数组
一维数组
int[] intArr = new int[10];int[] intArr = { 7, 3, 15, 8, 11, 6, 17,187,5,-6 };
二维数组
int[,] intArr = new int[2,3]{{1,2,3},{4,5,6},{7,8,9}} ;int[,] intArr = {{1,2,3},{4,5,6},{7,8,9}}; //逗号前表示第一层大括号数,以此类推
交错数组
int[][] nums=new int[2][]{new int[]{1,2},new int[] {3,4,5]};
foreach
foreach(类型 标识符 in 表达式){语句}
类型必须与表达式类型匹配也可以用模糊类型var
表达式可以使数组,字符串,集合等
int[] a={1,2,3,4,5,6};foreach(int b in a){Console.WriteLine(b);}
foreach只能读取不能修改,遍历整个表达式
排序
冒泡排序
int[] intArr = { 7, 3, 15, 8, 11, 6, 17,187,5,-6 };for(int i = 0; i<intArr.Length; i--) //第一层循环表示循环第几轮{for (int j = 0; j < intArr.Length - i-1 ; j--) //第二层循环表示每轮循环多少次{if (intArr[j] < intArr[j + 1]){int mid = intArr[j];intArr[j] = intArr[j + 1];intArr[j + 1] = mid;}}}
选择排序
int[] intArr = { 7, 3, 15, 8, 11, 6, 17,187,5,-6 };for(int i = 0; i < intArr.Length; i++){int index = i;int min = intArr[i];for(int j = i+1; j < intArr.Length; j++){if (intArr[j] < min){index = j;min = intArr[j];}}int mid = intArr[i]; //每轮选出当前最小值与第i项交换intArr[i] = min;intArr[index] = mid;}
插入排序
int[] intArr = { 7, 3, 15, 8, 11, 6, 17,187,5,-6 };for(int i = 0; i < intArr.Length-1; i++){for(int j = i+1; j >0; j--){if (intArr[j] < intArr[j-1]){int mid = intArr[j];intArr[j] = intArr[j-1];intArr[j-1] = mid;}}}