C#入門(數組排序,二維數組,鋸齒數組,輸出蛇形矩陣)

數組排序

冒泡排序

冒泡排序是數組的基礎排序方法

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 ();

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容