teaching machines

CS 145 Lab 6 – Arrays

October 31, 2014 by . Filed under cs145, fall 2014, labs.

First, if you have checkpoints left over from last lab, get them inspected during the first 15 minutes of this lab. No credit will be awarded past these 15 minutes.

Don’t forget to work in pairs! Where possible, please work with someone that you did not work with last week. The exchange of new ideas and perspectives is not an opportunity you want to rob yourself of.


In this lab you will learn about storing collections of data in arrays. Arrays let us number our data, making it easy to loop through the collection or associate data with the natural numbers.

Checkpoints 1 and 2

Solve two of the following problems:

  1. Suppose you have an array of 10 String names. You want to randomly select five of them for a drug test, using a Random object to facilitate randomness. Repeats are not allowed. Write code to accomplish this task.
  2. You have a list of people running for election stored in a String array. Enumerate all possible president/vice president pairs. For example, if the list contains Alice and Bob, then the possibilities are:
    President: Alice, Vice president: Bob
    President: Bob, Vice president: Alice
  3. A lot of data is impossible to use if it’s not sorted. (If you can find me an unsorted phonebook to use as an object lesson, I will be eternally grateful.) There are many algorithms for sorting data in an array. One simple one is called the selection sort. It can be described in pseudocode:
    for each cell in the list
      find the smallest value in the sublist starting at the current cell
      swap that smallest value with the value in the current cell

    Translate this algorithm into Java and sort an array of ints.