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

數(shù)組排序

冒泡排序

冒泡排序是數(shù)組的基礎(chǔ)排序方法

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

int temp = 0;

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

? ? for (int j = 0; j < intArray.Length - i -1; j++) {//每趟比較次數(shù)

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

? ?}



如何使用系統(tǒng)內(nèi)置的排序


Array.Sort (intArray);//系統(tǒng)內(nèi)置的排序方法是桶排序

foreach (var item in intArray) {

Console.WriteLine (item);

}

相對于自己寫的冒泡排序系統(tǒng)的內(nèi)置排序方法會更加快,冒泡排序只在數(shù)組中數(shù)字較少的時候,速度快。

一般來說系統(tǒng)內(nèi)置的排序方法,也就是桶排序,是最快的。


二維數(shù)組


二維數(shù)組的第一種定義方法

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 }

? ?};

二維數(shù)組的遍歷,也就是用兩個for循環(huán)嵌套輸出

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

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

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

// }

// Console.WriteLine ();

// }


定義二維數(shù)組的第二種方法

鋸齒數(shù)組

? ?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};

鋸齒數(shù)組也就是每行可能有不同的列的數(shù)組。


鋸齒數(shù)組的遍歷方法

for (int i = 0; i < twoim.Length; i++) { //twoim.Length 相當(dāng)于是二維數(shù)組的行數(shù)

for (int j = 0; j < twoim[i].Length; j++) {//twoim[i].Length 相當(dāng)于二維數(shù)組每行的列數(shù)

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

? ? }

? ? Console.WriteLine ();

? ?}

總結(jié)二維數(shù)組

第一種聲明格式:int[,] 遍歷訪問時要采取arr[i,j]的方式進行訪問

第二種聲明格式:int[][],此種寫法的二維數(shù)組實際上是由多個一維數(shù)組構(gòu)成,

可以不聲明列數(shù),但是必須聲明行數(shù),訪問方式是: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 ();

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容