首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

数组数据移动有关问题

2012-03-25 
数组数据移动问题有一数组如下:int targerIndex3//要移动的数组下标int newIndex0//将targerIndex要移

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

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;

热点排行