Ordered Array Class

Arrays are static data structures, so their size is fixed when they are created. Array elements are contiguous in RAM. This means that if you want to slot a value into the middle of an array, you need to shift the other values first. Imagine trying to slot yourself in between two people in a crowded cinema.

2018-09-19_06-43

A good exercise is to code an OrderedArray class. This is a wrapper for an array of Integer object (use Integers not ints so that we can check for nulls) that has an insert method that slots new values in ascending order.

I would say that the complexity of this code is about as tough as it gets at SL. If you need some scaffolding, use the class template below. Otherwise just have a go at it yourself. In addition, code a constructor that allows you to set the size of the array.

class Main {
  // This main class is just for testing.
  public static void main(String[] args) {
    OrderedArray oArr = new OrderedArray(50);
    for (int i = 0; i < 30; i++) {
      java.util.Random r = new java.util.Random();
      oArr.insert(r.nextInt(100));
    }
    // You will need to code this method.
    // The numbers should be in order.
    oArr.print();
  }  
}

class OrderedArray {

  // What instance variables will you need?

  public OrderedArray(int size) {
  // Use the size parameter to set the size of the array.
  }

  void insert(int n) {
  // Insert the new number in the right place.
  // 1. Find out where it should go.
  // 2. Make room for it.
  }

  void print() {
  // Print the numbers to the console.
  }
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s