日期:2014-05-18  浏览次数:20766 次

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

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;