Lecture #29 (Wednesday, Nov 29, 2006)

Daily Excercise One

Today we did our first daily excercise in order to get more familiar with actual programming. You were asked to write a sort() method that sorted the items currently in the array, and a standard toString().

```
// Turn in, as a lab, into the "daily1" directory

class SortableArrayCollection {

private Comparable[] items;
private int count;

private static final int DEFAULT_SIZE = 100;
private static final int GROWTH_COEFF = 2;

private void grow() {
Comparable[] biggerArray = new Comparable[GROWTH_COEFF * items.length];

for (int index=0; index < items.length; index++)
biggerArray[index] = items[index];

items = biggerArray;
}

public SortableArrayCollection(int size) {
items = new Comparable[size];
count = 0;
}

public SortableArrayCollection() {
items = new Comparable[DEFAULT_SIZE];
count = 0;
}

// 1. Write toString()

//Nice standard, simple toString() method for arrays
public String toString() {
String list = "";

for (int index=0; index < count; index++) {
list += items[index] + "/n";
}
return list;
}

//Added this insert in order method to use in sort()
public void insertInOrder(Comparable item) {

if (nextSlot == list.length)
grow();

int hole;
for (hole=nextSlot; hole > 0; hole--) {
if (list[hole-1].compareTo(item) < 0)
break;

list[hole] = list[hole-1];
}

list[hole] = item;
nextSlot++;
}

// 2. Write sort().
// Hint: Write an "insert in order" and add the items one at a time, possibly
// to a new array, or possibly in place

public void sort() {
//Making a new sortable array collection to add all the items into using the insertInOrder method
SortableArrayCollection sorted = new SortableArrayCollection(items.length);

//Walking through, adding each element into sorted
for(int index = 0; index < count; count++){
sorted.insertInOrder(items[count]);
}

//Set the array in this instance of the class to the array inside sorted
items = sorted.items;
}

}

```