我正在学习数组算法排序,有一个例子,我对Java中的以下数组删除代码感到很困惑。特别是在数组顺序上向左移动更高元素值的部分(从最开始的行(对于int k = j,k
public class ArrayApp {
public static void main(String args[]) {
int nElems = 10;
int[] arr = new int[nElems];
int j;
int searchKey;
arr[0] = 77;
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
System.out.println();
//Find 66 in array
searchKey = 66;
for (j = 0; j < nElems; j++) {
if (arr[j] == searchKey) {
break;
}
}
if (j == nElems) {
System.out.println("Cant find " + searchKey);
} else {
System.out.println("Found " + searchKey + " in position " + j);
}
//Remove 55 from array
searchKey = 55; // delete item with key 55
for (j = 0; j < nElems; j++) { // look for it
if (arr[j] == searchKey) {
break;
}
}
for (int k = j; k < nElems - 1; k++) { // move higher ones down
arr[k] = arr[k + 1];
}
nElems--;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
}
}
答案 0 :(得分:1)
您无法从数组中“删除”元素。数组具有固定长度。您只能移动元素来替换它。
原始阵列: 0 1 2 3 4 5 A B C D E F
让我们从中“删除”D
:
0 1 2 3 4 5
A B C D E F
A B C <------ Leave them as is
E F <--- Shift these to the left
Z <- Fill the vacant last element with something.
结果是
0 1 2 3 4 5
A B C E F Z
我希望这会有所帮助。
此循环执行移位。这里j
是要删除的元素的索引(上面的D
;它将是3)。从它开始,元素将一个索引值向左移动。
for (int k = j; // starting from the index of the element we trample.
k < nElems - 1; // up to the last element of the array.
k++ // incrementing k at every iteration
) {
// set element value (arr[k]) to the value to the right to it (arr[k+1])
arr[k] = arr[k + 1];
}
答案 1 :(得分:0)
一旦在数组中找到元素55,就知道该元素的索引。要删除此元素,您需要使用不同的值交换值。因此,loop
,其中k = j
将所有元素向前移动一个以移除该值。这样做的缺点是数组中的最后一个元素没有从数组中删除。但是,nElems
会减少,因此未来调用中的循环未达到此值。