下面的代码我已经将数组的中点设置为5但现在我想将中点移动到最后,当它移动到结尾时,其他数字将向左移动以填补空白。没有arraylists大声。
int mid = length/2;
for (int i = array.length-1 ; i> mid; i--) {
array[i] = array[i-1];
}
array[mid] = 5;
答案 0 :(得分: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;
}
答案 1 :(得分: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,6,7,8,9,5]中转换[1,2,3,4,5,6,7,8,9]。 这是你想要的吗?