首先告诉大家为什么我会自己去写一个数组的移位算法,原因是我在做组播服务器的后台程序中需要对播放列表的文件进行上一首,下一首的操作,此时操作的是文件加载到自定义的结构体数组中,上一首,下一首就是对该数组进行的移位操作:
class Program {
public static string[] str = new string[] { "1","2","3","4","5","6","7","8","9" };//用于测试的数组
public static string[] strTmp;//用来存放临时移动变量
//str是要进行移位的字符串数组,n是移动的次数
public static void FNext(string[] str, int n)
{
if (n < str.Length) //假设移动的次数小于数组的长度
{
if (str.Length / 2 < n) //把数组长度均等分成两份,而前半部分不大于后部分
{
//如果n大于前半部分,就将超出的这一部分进行移位
FNext(str, n-str.Length/2);
n = str.Length / 2;
}
str = new string[n];
for (int i = 0; i < str.Length; i++)
{
if (i == 0)
{
for (int j = 0; j < n; j++)
{
str[j] = str[j];
str[j] = str[j + n];
}
}
else
{
if (i < str.Length - n)
{
str[i] = str[i + n];
}
if (i == (str.Length - n))
{
for (int j = 0; j < n; j++)
{
str[j + str.Length - n] = str[j];
}
}
}
}
}
}
static void Main(string[] args)
{
FNext(Program.str, 9);
for (int i = 0; i < Program.str.Length; i++)
Console.WriteLine(Program.str[i].ToString());
Console.Read();
}
}
还有一种更简单更直接的方法,但可能也是效率最低的方法。就是将数组中的元素先移动一位,算法如下
public static void FNext(string[] str)
{
for (int i = 0; i < str.Length; i++)
{
if (i == 0)
{
Program.strTmp[0] = str[0];
str[0] = str[1];
}
else
{
if (i < (str.Length - 1))
{
str[i] = str[i + 1];
}
if (i==(str.Length-1))
{
str[str.Length-1] = Program.strTmp[0];
}
}
}
}
上面的理解应该比较容易,就是数组中的所有元素向左移动一次
public static void FNext(string[] str, int n)
{
for (int i = 0; i < n; i++)
{
FNext(str);
}
}
这个函数将向左移动重复n次,也就是向左移动了n个位置
呵呵,和大家分享下,自己也蛮开心的
转载于:https://blog.51cto.com/gadil/343360