void removeAll( E item ) // removes all occurrences of the given item
{
while ( remove(item) ) { // remove a single occurrence, try again
;
}
}
Our hunch was that the running time of removeAll is O(n^2):
remove n timesremove may need to go through the whole list, i.e. examine n boxesO(n^2) running time. (We will use big-O below even when big-Ω or big-Θ are more appropriate.)
We used a couple of estimates (no need to be precise, just convincing):
7→7→7→...7→8:
cycle work details work list 7→7→7→...7→81.
- inspects
n-1boxes with 7s:3(n-1)units work- deletes the last 8: 6 units of work
3(n-1)+6 7→7→7→...72.
- inspects
n-1boxes with 7s:3(n-1)units work- done, no 8 found
3(n-1) 7→7→7→...7Total work: 3(n-1) + 6 + 3(n-1) = 3n, soO(n). Did not reach our goal.
8→8→8→...8→8:
cycle work details work list 8→8→8→...8→81.
- deletes first 8 right away: 6 units of work
6 8→8→...8→82.
- deletes first 8 right away: 6 units of work
6 8→...8→8... n-1.
- deletes first 8 right away: 6 units of work
6 8n.
- deletes first 8 right away: 6 units of work
6 emptylast.
- done, no 8 found
2 emptyTotal work: 6n + 2, soO(n). Did not reach our goal.
7→7→7→...→7→8→8→8...→8:
cycle work details work list 7→7→7→...→7→8→8→8...→81.
- inspects
n/2boxes with 7s:3(n/2)units work- deletes first 8: 6 units of work
3(n/2)+6 7→7→7→...→7→8→8...→82.
- inspects
n/2boxes with 7s:3(n/2)units work- deletes first 8: 6 units of work
3(n/2)+6 7→7→7→...→7→8...→8... n/2.
- inspects
n/2boxes with 7s:3(n/2)units work- deletes first 8: 6 units of work
3(n/2)+6 7→7→7→...→7last.
- done, no 8 found
2 emptyTotal work: n/2*(3(n/2) + 6) + 2 = 3/4n^2 + 3n + 2, soO(n^2). Reached the goal.
8→8→8→...→8→7→7→7...→7:
cycle work details work list 8→8→8→...→8→7→7→7...→71.
- ?
? ? 2.
- ?
? ? ... ?
- ?
? ? last.
- ?
? ? Total work: ?
cycle work details work list 7→8→7→8→7→8...→7→81.
- ?
? ? 2.
- ?
? ? ... ?
- ?
? ? last.
- ?
? ? Total work: ?