美文网首页
C#入门(数组排序,二维数组,锯齿数组,输出蛇形矩阵)

C#入门(数组排序,二维数组,锯齿数组,输出蛇形矩阵)

作者: Unity学习的路上 | 来源:发表于2016-12-03 16:03 被阅读0次

数组排序

冒泡排序

冒泡排序是数组的基础排序方法

int[] intArray = { 1, 5, 5, 79, 54, 10, 55, 15 };

int temp = 0;

for (int i = 0; i < intArray.Length; i++) { //控制趟数

    for (int j = 0; j < intArray.Length - i -1; j++) {//每趟比较次数

     if (intArray [j] > intArray [j + 1]) {//交换位置

      temp = intArray [j];

      intArray [j] = intArray [j + 1];

      intArray [j + 1] = temp;

     }

    }

   }

   Console.WriteLine (sw.Elapsed);

   foreach (var item in intArray) {

    Console.WriteLine (item);

   }

如何使用系统内置的排序

Array.Sort (intArray);//系统内置的排序方法是桶排序

foreach (var item in intArray) {

Console.WriteLine (item);

}

相对于自己写的冒泡排序系统的内置排序方法会更加快,冒泡排序只在数组中数字较少的时候,速度快。

一般来说系统内置的排序方法,也就是桶排序,是最快的。

二维数组

二维数组的第一种定义方法

int[,] twoint = new int[3,3];

int[,] twoim = {

{ 1, 2, 34, 8, 4 },

    { 4, 8, 6, 4, 3 },

    { 8, 4, 87, 6, 45 },

    { 12, 10, 5, 7, 9 }

   };

二维数组的遍历,也就是用两个for循环嵌套输出

for (int i = 0; i < 4; i++) {

// for (int j = 0; j < 5; j++) {

// Console.Write (twoim[i,j] + " ");

// }

// Console.WriteLine ();

// }

定义二维数组的第二种方法

锯齿数组

   int[][] twoim = new int[3][];

   twoim [0] = new int[]{ 1, 2, 3 };

   twoim [1] = new int[]{ 1, 2, 3,4};

   twoim [2] = new int[]{ 1, 2, 3,4,5};

锯齿数组也就是每行可能有不同的列的数组。

锯齿数组的遍历方法

for (int i = 0; i < twoim.Length; i++) { //twoim.Length 相当于是二维数组的行数

for (int j = 0; j < twoim[i].Length; j++) {//twoim[i].Length 相当于二维数组每行的列数

Console.Write(twoim[i][j]);

    }

    Console.WriteLine ();

   }

总结二维数组

第一种声明格式:int[,] 遍历访问时要采取arr[i,j]的方式进行访问

第二种声明格式:int[][],此种写法的二维数组实际上是由多个一维数组构成,

可以不声明列数,但是必须声明行数,访问方式是:arr[i][j];

//输入n(n < 10),代表矩阵n*n,输出蛇形矩阵。

//例如:n = 3时,输出:

//1 2 3

//8 9 4

//7 6 5/

/n = 4时,输出:

//1  2  3  4

//12 13 14  5

//11 16 15  6

//10 9  8  7

//int n = int.Parse (Console.ReadLine ());

int[,] intArray = new int[n,n];

for (int i = 0; i < n; i++) 

{

for (int j = 0; j < n; j++) 

{

intArray [i,j] = 0;

}

}

int value = 1;

int max = n * n;

int a = 0;

int b = 0;

intArray [a, b] = value;

for (;value<max;)

while (b + 1 < n && intArray [a, b + 1] == 0) {  //向右

intArray [a, ++b] = ++value;

}

while (a + 1 < n && intArray [a + 1, b] == 0) {  //向下

intArray [++a, b] = ++value;

}

while (b - 1 >= 0 && intArray [a, b - 1] == 0) {  //向左

intArray [a, --b] = ++value;

}

while (a - 1 >= 0 && intArray [a - 1, b] == 0) {  //向上

intArray [--a, b] = ++value;

}

}

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

Console.Write (intArray[i,j]+" ");

}

Console.WriteLine ();

}

相关文章

网友评论

      本文标题:C#入门(数组排序,二维数组,锯齿数组,输出蛇形矩阵)

      本文链接:https://www.haomeiwen.com/subject/sejcmttx.html