Data Structures, Algorithms, & Applications in Java
Chapter 5, Exercise 9
The method dataStructures.ArrayLinearListWithRemoveRange.removeRange
is given below.
/** remove the elements whose index is in the range
* start through finish-1 */
public void removeRange(int start, int finish)
{
// validate start and finish indexes
if (start < 0)
start = 0;
if (finish > size)
finish = size;
if (start >= finish)
// no elements to remove
return;
// move elements whose index is finish ... size-1 left
int numberAtRightOfRange = size - finish;
System.arraycopy(element, finish, element, start, numberAtRightOfRange);
// set size and replace vacated slots with null
int newSize = start + numberAtRightOfRange;
while (size != newSize)
element[--size] = null; // enable garbage collection
}
It takes
O(size - finish) time to move the elements
at the right of the removed range to their new positions;
and it takes O(finish - start) time to replace
the removed elements with null.
So, the total time is
O(size - start).