-4

下面的代码我已将数组的中点设置为 5,但现在我想将中点移动到最后,当它移动到最后时,其他数字将向左移动以填补空白。没有阵列列表大声。

        int mid = length/2;

    for (int i = array.length-1 ; i> mid; i--) { 
        array[i] = array[i-1]; 
    } 
    array[mid] = 5;
4

2 回答 2

1

像这样的东西?

int mid = array.length/2;

for (int i = mid; i < array.length-1; i++)
{
    int temp = array[i];
    array[i] = array[i+1];
    array[i+1] = temp;
}
于 2013-03-01T16:57:50.653 回答
0
public static void main(String[] args) {
    int array[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int mid = array.length / 2;
    array[mid] = 5;

    // my code starts here...

    int aux = mid; // aux isn't necessary if you can lost mid value
    int backup = array[mid]; // save the middle value

    for (; aux < array.length - 1; aux++) { //starting at middle until the end of array
        // current pos receives the next value;
        array[aux] = array[aux + 1];
    }

    array[array.length - 1] = backup; // restore the middle value at the end;
}

该代码将 [1, 2, 3, 4, 5, 6, 7, 8, 9] 转换为 [1, 2, 3, 4, 6, 7, 8, 9, 5]。是你想要的吗?

于 2013-03-01T17:01:53.610 回答