Last time:
static void bubbleSort1(List<Integer> xs) {
for (int ii = 0; ii < xs.size(); ++ii) {
for (int jj = 0; jj < xs.size() - 1; ++jj) {
int vv0 = xs.get(jj);
int vv1 = xs.get(jj + 1);
if (vv0 > vv1) {
// swap
xs.set(jj, vv1);
xs.set(jj + 1, vv0);
}
}
}
}
This time:
static void bubbleSort2(List<Integer> xs) {
for (int ii = 0; ii < xs.size(); ++ii) {
ListIterator<Integer> it = xs.listIterator();
while (it.nextIndex() < xs.size() - 1) {
int vv0 = it.next();
int vv1 = it.next();
if (vv0 > vv1) {
// swap
it.set(vv0); //
// first previous gets jj+1 again
it.previous();
// this gets us back to jj
it.previous();
it.set(vv1);
it.next();
}
else {
it.previous();
}
}
}
}
Which version is faster with LinkedList? ArrayList? Which version is better?
How does an ArrayList work? #
- An array of items.
- Separate size and capacity.
- Double size when full.
Let’s build our our own List. #
Make ConsList (with the interface) implement some of the List interface.