# Class 36: Arrays

Back to When Things Go Wrong. On to Exam 2.

Held: Friday, 4 April 2003

Summary: Today we visit one of Java's core data structures: the array. We consider two applications of arrays in writing algorithms.

Related Pages:

Notes:

• We may have admitted students visiting today.
• Some of you have asked about extra credit on exams and homework. Since I grade exams and homework differently, the ways in which I award extra credit differs. On homework, the base grade for correct work is B. You need extra credit to bring your grade up to an A. On exams, the base grade is 100 and you only lose points for incorrect answers. Extra credit is less necessary.
• Are there questions on homework 3?
• I plan to make object-oriented design the subject of next week's classes. No need to read ahead over the weekend.
• Next Tuesday we'll meet in Saint's Rest.

Overview:

• Introduction to Arrays.
• Arrays in Java.
• An Application: Fibonacci Numbers.
• An Application: Box Packing.

## Arrays

• Data structures in programming languages allow us to organize and manipulate data in more natural ways.
• You've already seen one way data structures are helpful: classes are, in effect, one way to build your own data structurs.
• For example, your `Rational` classes allowed you to group logical aspects of a rational number into a whole.
• But sometimes you want to collect an unknown amount of information, just as you do with Scheme's lists and vectors.
• As importantly, you want to be able to visit the items one-by-one.
• Many languages provide arrays to support this type of collection.
• Traditionally, arrays are fixed-sized collections of elements that you can index by number.
• However, different languages provide different perspectives.

### Arrays in Java

• Java provides one form of arrays, although with some interesting design decisions.
• When you create an array, you must specify its length in advance.
• Array indices range from 0 to length-1.
• Arrays are somewhat homogeneous: all the elements are of the same type (or a subclass of the same type).
• You can declare arrays of a particular size with
```type[] name = new type[size];
```
• For example, to create a collection of five numbers named `stuff`, you would write
```double[] stuff = new double[5];
```
• You can also fill in arrays when you create them. To do this, you would write
```type[] name = { val1, val2, ..., valn }
;
```
• For example, to create an array of integers with the values 3, 2, 6, and 5, I would write
```int[] stuff = {3, 2, 6, 5};
```
• Note that you don't need to indicate the size.
• You can refer to a particular element of an array with `name[index]`
• For example, I could element 3 of the `stuff` with `stuff[3]`
• You can also use variables (or even expressions) as indices. For example, if `i` held the value 3, then we could get element 3 of the `stuff` with `stuff[i]`
• You can always determine the number of elements in an array with `name.length`
• Once we have values in arrays, it's "easy" to do general computations with them. Here is a method that sums the values in an array.
```public double sum(double[] stuff) {
double total = 0;     // The total of the numbers in stuff
int i;                // A counter variable for stepping through
// the array
// Step through the array, adding each subsequent value
for(i = 0; i < stuff.length; i = i + 1) {
total = total + stuff[i];
}
// Return the total value
} // sum
```

## Example: The Fibonacci Sequence

• We'll start by looking at a procedure used to compute the Fibonacci sequence.
• In case you've forgotten (or don't know), the sequence has the form 0 1 1 2 3 5 8 13 21 ...
• That is, each number (except the first two) is the sum of the previous two numbers.
• Why is this an interesting sequence?

### A Recursive Implementation

• We can, of course, write a recursive solution to computing the nth Fibonacci number.
```  public static long fib(int n) {
if (n < 2)
return n;
else
return fib(n-1) + fib(n-2);
} // fib(int)
```
• It's short, it's elegant. it's recursive. What's not to like?
• Well, let's consider the efficiency.
• In effect, we do two recursive calls for each call and we don't shrink the parameter much.
• Informally, that makes it an exponential algorithm.

### An Iterative Implementation

• We can use arrays to improve the running time of our recursive Fibonacci algorithm.
• How? The biggest problem with the recursive Fibonacci is that we recompute values again and again.
• Rather than recomputing them, we'll store them in an array which we compute from left-to-right.
• Once we've computed all the values in the array of size n+1, we can easily return the nth Fibonacci number.

## Another Example: Grain Packing

• Suppose we were in charge of putting boxes on a specialized UPS truck.
• Each box has a size (amount of space it occupies) and a value to UPS for shipping it on the truck.
• How do we maximize the value for the given space?
• We'll start by making two dangerous simplifying assumptions:
• If the sum of volumes of the boxes selected is less than or equal to the volume of the truck, we can fit it in the truck.
• There are an infinite number of each value/size combination
• One solution is greedy: repeatedly pick the most valuable package that still fits.
• What is the running time of that solution?
• Does that solution work?
• Another solution is exhaustive: try every combination and find the best.
• What is the running time of that solution?
• Does that solution work?

### Box Packing with Arrays

• Can arrays help us make the solution better?
• Just as we used an array to cache partial results in the Fibonacci solution, we'll use an array to cache partial results in this solution.
• What are the partial results? The best possible choice for each size of truck.
• Implementation to be filled in by the class.
• Can we make this better?

## History

Thursday, 15 January 2003 [Samuel A. Rebelsky]

• Created as a mostly-blank outline.

Back to When Things Go Wrong. On to Exam 2.

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Tue May 6 09:20:54 2003.
The source to the document was last modified on Thu Jan 16 15:16:14 2003.
This document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CS153/2003S/Outlines/outline.36.html`.

You may wish to validate this document's HTML ; ; Check with Bobby

Samuel A. Rebelsky, rebelsky@grinnell.edu