Algorithms and OOD (CSC 207 2014S) : EBoards

CSC 207 2014S: Extra Session, Week 6




Why don't you like syntax coloring?

Distracting. Sometimes confusing.

Talk about good code design

Process concepts:

A bad example

for (int i = 0; i < str.length(); i++) { this.contents[start+i] = str.toCharArray()[i]; } // for


A better version

int strlen = str.length(); char[] strchars = str.toCharArray(); for (int i = 0; i < strlen; i++) { this.contents[start+i] = strchars[i]; } / for

But, doesn't show knowledge of the library. E.g., String.charAt, which we could assume is constant time.

int strlen = str.length(); for (int i = 0; i < strlen; i++) { this.contents[start+i] = str.charAt(i); } / for

But there's more to the library. System.arraycopy is intended to do quick copying of values.

System.arraycopy(str.toCharArray(), 0, this.contents, start, str.length());

The result is shorter (in terms of code we write), more likely to be correct, likely to be faster, and potentially more readable.

An example of clarity

Problem: Insert an array into the middle of another array

First model: Three loops (or three calls to System.arraycopy)

// Deal with the stuff before the insertion point
// Deal with the stuff after the insertion point
// Deal with the inserted stuff

Second model: One loop, asking where we are at each point

for each position in the target array
   if we're before the insertion point ...
   if we're in the insertion section
   if we're after the insertion section

In case it's not clear, Sam would suggest the first.

Thinking about replace

// Copy the characters from the replacment // Shift the remaining stuff over (vague)

O(logn) algorithms

Although we say the constant multipler doesn't really matter, it makes a HUGE difference for O(log_2(n)) algorithms.

Suppose we have an O(log_2(n)) algorithm that can process a million-item collection in a minute

How big a collection can an algorithm that is twice as fast process in a minute? Now, we can do billion-element collection.

Copyright (c) 2013-14 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.