本文實例分析了C#數組反轉與排序的方法。分享給大家供大家參考。具體實現方法如下:
C#數組反轉
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 數據反轉
{
class Program
{
static void Main(string[] args)
{
string[] strAllay = { "毛澤東", "李世民", "秦始皇", "成吉思汗", "習近平","鄧小平"};
string s;
for (int i = 0; i < strAllay.Length / 2; i++)//strAllay.Length/2是因為經過(將數組的長度值除以2)次就可以將數組成員進行反轉了
{
s = strAllay[i];
strAllay[i] = strAllay[strAllay.Length - 1 - i];//如果i等于數組第一項值(毛澤東)的時候,將它與最后一個值(鄧小平)互換。
strAllay[strAllay.Length - 1 - i] = s;
}
foreach (string ss in strAllay)
{
Console.Write(ss+" " );
}
Console.ReadKey();
}
}
}
C#數組排序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 數組
{
class Program
{
static void Main(string[] args)
{
//輸出一個數組里的最大的數值;
/*
int[] arr = new int[] { 10, 9, 15, 6, 24, 3, 0, 7, 19, 1 };
int max = 0;
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
Console.WriteLine(max);
**/
//按大小順序輸出數組的值
int[] list = new int[] { 10, 9, 15, 6, 24, 3, 0, 7, 19, 1 ,100,25,38};
/*
for (int i = 0; i < list.Length-1; i++)
{
for (int j = i+1; j < list.Length; j++)
{
if (list[i] > list[j])
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}*/
/// <summary>
/// 插入排序法
/// </summary>
/// <param name="list"></param>
for (int i = 1; i < list.Length; i++)
{
int t = list[i];
int j = i;
while ((j > 0) && (list[j - 1] > t))
{
list[j] = list[j - 1];
--j;
}
list[j] = t;
}
foreach (int forStr in list)
{
Console.Write(forStr + " ");
}
Console.ReadKey();
}
}
}
希望本文所述對大家的C#程序設計有所幫助。