Hidden Complexity

In AP we've been playing with ArrayLists. The problem for today?
Create an ArrayList with consecutive integers and then write a routine
that will randomize the ArrayList.

For example, you might start with this ArrayList:

0,1,2,3,4,5

and end up with

3,5,1,4,2,0

First cut, the students grabbed a random element from the ArrayList,
removed it, and added it to the end of a new list. Then repeat until
the original list is empty and the new one is randomized. Then return
the list.

Then it was time to time. Both seemed pretty quick but as our data set
grew things seemed strange:

Size

Time

100,000

2 seconds

200,000

7 seconds

400,000

26 seonds

We're just looping through an ArrayList, what's going on? When we
double the size of the list, it should just take double the time.

Since the class already wrote their own ArrayList implementation, they
were quick to realize that every time we removed an item from the
original Array, we were doing a linear or O(n) operation. That means
our algorithms, which look linear, are in fact O(N2).

Can we do better? You bet. They just changed the remove and add to
using get and set. Instead off removing an item and re-inserting it,
just swap the randomly selected item with the last element: