C# 基本算法

时间:2022-04-02 15:41:02

1、冒泡排序

  排序

int[] ArrayList = new int[] {,,,,,, };
for (int i = ; i < ArrayList.Count(); i++)
{
for (int j = i; j < ArrayList.Count(); j++)
{
int temp = ;
if (ArrayList[i]>ArrayList[j])
{
temp = ArrayList[j];
ArrayList[j] = ArrayList[i];
ArrayList[i] = temp;
}
}
}

2、递归算法

  一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少。

public static int RecursiveAlgorithm(int num)
{
int numOut=;
if (num==||num==)
{
numOut = ;
}
else
{
numOut = RecursiveAlgorithm(num-) + RecursiveAlgorithm(num - );
}
return numOut;
}

3、字符串反转

public static string Sort1(int[] num)
{
int temp;
for (int i = ; i < num.Length; i++)
{
for (int j = i+; j < num.Length; j++)
{
if (num[i]<num[j])
{
temp = num[j];
num[j] = num[i];
num[i] = temp;
}
}
}
StringBuilder sb = new StringBuilder();
foreach (var item in num)
{
sb.Append(item+"|");
}
return sb.ToString();
} public static string Sort2(int[] num)
{
int temp;
for (int i = ; i < num.Length; i++)
{
temp = num[i];
int j = i;
while (j > && num[j - ] > temp)
{ //通过盘点,值一次次提前
num[j] = num[j - ];
--j;
}
num[j] = temp;
}
StringBuilder sb = new StringBuilder();
foreach (var item in num)
{
sb.Append(item + "|");
}
return sb.ToString();
} public static string test1(string str)
{
Char[] arr = str.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
public static string Test2(string str)
{
int length = str.Length;
char[] chr = new char[length];
for (int i = ; i < length; i++)
{
chr[i] =str[length-i-];
}
return new string(chr);
} public static string Test3(string str)
{
StringBuilder sb = new StringBuilder(str.Length);
for (int i = ; i < str.Length; i++)
{
sb.Append(str[str.Length-i-]);
}
return sb.ToString();
}