这是我的代码:
private void shrink(){
int length = top+1;
if(length<=MINCAPACITY || top<<2 >= length)
return;
length = length + (top<<1);
if(top < MINCAPACITY) length = MINCAPACITY;
int[] newstack = new int[length];
System.arraycopy(stackRep, 0 , newstack, 0 , top+1);
stackRep = newstack;
}
在我的书中,据说如果超过3/4空,此操作会将数组缩小一半。任何人都可以向我解释这个代码是如何发生的?我怀疑这个操作发生在第一个if语句和长度语句中?
答案 0 :(得分:0)
Java数组不能改变长度。这样做,是计算新长度,创建一个新长度的数组,并从旧数组中复制内容,然后使旧数组引用新数组。
int length = ... // this will be the new arrays length
int[] newstack = new int[length]; // this is the new array
System.arraycopy(stackRep, 0 , newstack, 0 , top + 1); // stuff is copied to the new array
stackRep = newstack; // old array is now the new array
不确定这是否回答了您的问题
修改强>
通过“改变长度的部分”,我假设您想知道这些是做什么的:<<
和>>
。它们是bithift运算符,您可以找到有关它们的更详细说明,例如here。
基本上他们这样做:
x << n
- 将x
与2
相乘n
的力量x >> n
- 将x
除以2
n
所以10 << 1
是20
。 10 << 3
是80
。 10 >> 1
是5
。 10 >> 2
为2
(此处精度丢失,因为这些运算符只是移位)。
答案 1 :(得分:0)
我遵循以上逻辑,如果超过3/4的空白为空,则不会将数组缩小为一半。
我认为您正在遵循narasimha karumanchi在Java中简化的数据结构和算法。您在此处共享了相同的代码段。
我对代码做了很少的更改。请找到以下代码。如果超过3/4的空白,它将把数组缩小到一半。
private void shrink(){
int length = top+1;
if(length<=MIN_CAPACITY || top<<2 >= stackRep.length){
return;
}
length = (length<<1);
if(top < MIN_CAPACITY) length = MIN_CAPACITY;
int[] newstack = new int[length];
System.arraycopy(stackRep, 0 , newstack, 0 , top+1);
stackRep = newstack;
}
假定堆栈中有16个元素,并且数组的大小也为16。由于数组已满,因此创建了另一个数组,新数组的大小为原来的两倍,并且创建了32个数组,并将旧数组内容复制到新数组和第17个元素中条目将被放入新数组。 让我们通过弹出元素进行跟踪。假设MIN_CAPACITY = 2
堆栈17中没有元素,数组大小为32,顶部= 16
在弹出后,如果堆栈中仅剩下数组元素的1/4大小,则
堆栈8中没有元素,数组大小为32,顶部= 7
top << 2就是top * 2 * 2,所以(top << 2> = stackRep.length)将变为(28> 32),这是错误的。 现在我们应该创建一半大小的数组。
length =(长度<< 1);将创建一半大小的数组。
其余的东西都是自我解释。