读书人

数组数据移动有关问题

发布时间: 2012-03-25 20:55:16 作者: rapoo

数组数据移动问题
有一数组如下:

int targerIndex=3;//要移动的数组下标
int newIndex=0;//将targerIndex要移动到数组的下标

string []str={1,27,3,12};


最后得到数组结果应为:{12,1,27,3} //显然是数据向后移


根据以上targerIndex、newIndex如何实现以上结果呢,请指教!



[解决办法]

C# code
static void MoveItem<T>(T[] arr, int from, int to){    int delta = from > to ? 1 : from < to ? -1 : 0;    T moving = arr[from];    for (int i = to; i != from; i += delta)    {        T tmp = arr[i];        arr[i] = moving;        moving = tmp;    }    arr[from] = moving;}
[解决办法]
int lowIndex = targetIndex > newIndex ? newIndex: targetIndex;
int highIndex = targetIndex > newIndex ? targetIndex : newIndex;
string tmp = str[highIndex];
for(int i = highIndex; i > lowIndex; i--)
{
str[i] = str[i - 1];
}
str[lowIndex] = tmp;

读书人网 >C#

热点推荐