1. Sorting

This week's lab explores different algorithms for sorting.

  • You can sort any type of data, as long as they are comparable
  • These sorting algorithms are "in place": they don't use additional memory

1.1 Double-Trouble Sort

Compare each item with all others, and swap them if they are in the wrong order.

1.2 Bubble Sort

Compare each item with the next, and swap them if you must. Repeat until no swaps are made.

1.3 Quicksort

Divide the list in half and quicksort the halves. Combine the halves.

2. Files

2.1 Writing Text Files

  • Writing to a file can cause an error (and Exception) and you must "catch it"

First, we import some IO functions:

  • FileWriter - does the low-level writing
  • BufferedWriter - wraps around FileWriter
  • FileReader - does the low-level reading
  • BufferedReader - wraps around the FileReader

Reading and writing is slow, if you do it character-by-character. If you can handle a bunch at once, that is more efficient. The "buffer" adds a place to store a bunch of characters coming in or out.

In [1]:
import java.io.*;

A writer provides a method write(String). Note that it doesn't add a newline on the end. You have to do that manually.

Most importantly, Java requires that you "catch" any errors (eg, Exceptions) that can happen. If you don't catch them, you can't compile the code. (Java9 interpreter actually allows you to skip this part.)

When you catch it, you can do "handle the problem."

The lower level code must be "throwing" these Exceptions.

In [2]:
String fileName = "temp.txt";

try {
    FileWriter fileWriter = new FileWriter(fileName);

    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

    bufferedWriter.write("Hello there,");
    bufferedWriter.write(" here is some text.");
    bufferedWriter.write("We are writing");
    bufferedWriter.write(" the text to the file.");

} catch(IOException ex) {
    System.out.println("Error writing to file '" + fileName + "'");
|  Added variable fileName of type String with initial value "temp.txt"

2.2 Reading Text Files

Reading works

In [5]:
String line = null;

try {
    FileReader fileReader = new FileReader(fileName);
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    while((line = bufferedReader.readLine()) != null) {

} catch(FileNotFoundException ex) {
    System.out.println("Unable to open file '" + fileName + "'");                
} catch(IOException ex) {
    System.out.println("Error reading file '" + fileName + "'");                  
|  Modified variable line of type String with initial value null

 } catch(IOException ex) {
Hello there, here is some text.
We are writing the text to the file.

2.3 Compiling Java Programs

In [39]:
! javac *.java
In [ ]:
! java Game Game.game