i traced above logic, it is not shrinking the array to half if more than 3/4th is empty.
I think you are following data structures and algorithms made easy in java by narasimha karumanchi. you have shared same code snippet here.
i made few changes to the code. Please find the following code. It will shrinks the array to half if more than 3/4th empty.
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;
}
assume there are 16 elements in stack and size of array is also 16. one more element is added, since array is full new array with double the size 32 is created and old array contents will be copied to new array and 17th element entry will be made into new array.
let us trace by popping elements. assume MIN_CAPACITY=2
no of elements in stack 17, array size 32, top = 16
after popping if there are only 1/4th size of the array elements left in the stack then
no of elements in stack 8, array size 32, top = 7
top << 2 is nothing but top * 2 * 2 so (top<<2 >= stackRep.length) will become (28 > 32), which is false.
now we should create array with half the size.
length = (length<<1); will create array with half the size.
rest of the things are self explanatory.