C#语言基础
lesson#4 排序算法+二维数组
内容:
1. 选择排序;
2. 二维数组;
3. Foreach循环;
1. 选择排序;
//练习题1:
//用选择排序法排列数组下列数组并打印排序后的数组:
double[] arr = { 12, 90, 14, 85, 34, 9, 23, 55, 10.5, 8 };
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] > arr[j])
{
double temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
foreach (double a in arr) { Console.WriteLine(a); }
2. 二维数组;
//有两下标的数组称为二维数组
int[] a;
//动态初始化
int[,] b = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
//b = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
//b = new int[2, 3];
//静态初始化
int[,] c = { { 1, 2, 3 }, { 4, 5, 6 } };
//Console.WriteLine(b[1,1]);
b[1, 0] = 7;
for (int i = 0; i < b.GetLength(0); i++)
{
//i=0,1
for (int j = 0; j < b.GetLength(1); i++)
{
Console.Write(b[i, j]);
}
Console.WriteLine();
}
//练习
//将一个二维数组的行和列交换,存储到另外一个数组中去
int[,] arr = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
int[,] brr = new int[arr.GetLength(1), arr.GetLength(0)];
for (int i = 0; i < brr.GetLenth(0); i++)
{
for (int j = 0; j < brr.GetLenth(1); j++)
{
brr[i, j] = arr[j.i];
Console.Write(brr[i, j]);
}
}
Console.WriteLine();
3. foreach循环;
int[] a = { 1, 2, 3, 4, 5 };
int[,] b = { { 1, 2, 3 }, { 4, 5, 6 } };
foreach (var item in a)
{
Console.WriteLine(item);
}