Skip to content

Commit

Permalink
Adds indegree() to Digraph and EdgeWeightedDigraph; upgrades Insertio…
Browse files Browse the repository at this point in the history
…nX to use binary insertion sort
  • Loading branch information
kevin-wayne committed Sep 10, 2015
1 parent 89f4f53 commit 7108dc6
Show file tree
Hide file tree
Showing 19 changed files with 206 additions and 65 deletions.
8 changes: 4 additions & 4 deletions README-MAVEN.txt
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,15 @@ Using Maven from the Windows Command Prompt
Download and install Maven by following the instructions at
https://maven.apache.org.

Locate the installation directory for Maven, e.g., C:\<appache-maven-x-y-z>
Locate the installation directory for Maven, e.g., C:\<apache-maven-x-y-z>

Locate the installation directory for Java, e.g., C:\Program Files\Java\<JDK-x-y-z>

Set the following environment variables:

set JAVA_HOME=C:\Program Files\Java\<JDK-x-y-z>
set PATH=%JAVA_HOME%\bin;%PATH%
set M2_HOME=C:\<appache-maven-x-y-z>
set M2_HOME=C:\<apache-maven-x-y-z>
set PATH=%M2_HOME%\bin;%PATH%

To create the algs4-<version>.jar package and install it in the local
Expand All @@ -89,15 +89,15 @@ Download and install Maven, either by using your favorite package
manager (such as apt-get) or by following the instructions at
https://maven.apache.org.

Locate the installation directory for Maven, e.g., /my/maven/<appache-maven-x-y-z>
Locate the installation directory for Maven, e.g., /my/maven/<apache-maven-x-y-z>

Locate the installation directory for Java, e.g., /my/java/<JDK-x-y-z->

Set the following environment variables:

export JAVA_HOME=/my/java/<JDK-x-y-z>
export PATH=$JAVA_HOME/bin:$PATH
export M2_HOME=/my/maven/<appache-maven-x-y-z>
export M2_HOME=/my/maven/<apache-maven-x-y-z>
export PATH=$M2_HOME/bin:$PATH

To create the algs4-<version>.jar package and install it in the local
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/edu/princeton/cs/algs4/BinarySearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ private BinarySearch() { }
/**
* Returns the index of the specified key in the specified array.
*
* @param key the search key
* @param a the array of integers, must be sorted in ascending order
* @param key the search key
* @return index of key in array <tt>a</tt> if present; <tt>-1</tt> otherwise
*/
public static int indexOf(int key, int[] a) {
public static int indexOf(int[] a, int key) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
Expand All @@ -74,10 +74,10 @@ public static int indexOf(int key, int[] a) {
* @param key the search key
* @param a the array of integers, must be sorted in ascending order
* @return index of key in array <tt>a</tt> if present; <tt>-1</tt> otherwise
* @deprecated Replaced by {@link #indexOf(int, int[])}.
* @deprecated Replaced by {@link #indexOf(int[], int)}.
*/
public static int rank(int key, int[] a) {
return indexOf(key, a);
return indexOf(a, key);
}

/**
Expand All @@ -97,7 +97,7 @@ public static void main(String[] args) {
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
if (BinarySearch.indexOf(key, whitelist) == -1)
if (BinarySearch.indexOf(whitelist, key) == -1)
StdOut.println(key);
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/edu/princeton/cs/algs4/BinarySearchST.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public BinarySearchST() {
}

/**
* Initializes an empty symbol table with the given initial capacity.
* Initializes an empty symbol table with the specified initial capacity.
*/
public BinarySearchST(int capacity) {
keys = (Key[]) new Comparable[capacity];
Expand Down Expand Up @@ -139,7 +139,7 @@ public Value get(Key key) {
}

/**
* Return the number of keys in the symbol table strictly less than <tt>key</tt>.
* Returns the number of keys in the symbol table strictly less than <tt>key</tt>.
*
* @param key the key
* @return the number of keys in the symbol table strictly less than <tt>key</tt>
Expand All @@ -148,11 +148,11 @@ public Value get(Key key) {
public int rank(Key key) {
int lo = 0, hi = N-1;
while (lo <= hi) {
int m = lo + (hi - lo) / 2;
int cmp = key.compareTo(keys[m]);
if (cmp < 0) hi = m - 1;
else if (cmp > 0) lo = m + 1;
else return m;
int mid = lo + (hi - lo) / 2;
int cmp = key.compareTo(keys[mid]);
if (cmp < 0) hi = mid - 1;
else if (cmp > 0) lo = mid + 1;
else return mid;
}
return lo;
}
Expand Down
29 changes: 24 additions & 5 deletions src/main/java/edu/princeton/cs/algs4/Digraph.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@
public class Digraph {
private static final String NEWLINE = System.getProperty("line.separator");

private final int V;
private int E;
private Bag<Integer>[] adj;
private final int V; // number of vertices in this digraph
private int E; // number of edges in this digraph
private Bag<Integer>[] adj; // adj[v] = adjacency list for vertex v
private int[] indegree; // indegree[v] = indegree of vertex v

/**
* Initializes an empty digraph with <em>V</em> vertices.
Expand All @@ -68,14 +69,15 @@ public Digraph(int V) {
if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative");
this.V = V;
this.E = 0;
indegree = new int[V];
adj = (Bag<Integer>[]) new Bag[V];
for (int v = 0; v < V; v++) {
adj[v] = new Bag<Integer>();
}
}

/**
* Initializes a digraph from an input stream.
* Initializes a digraph from the specified input stream.
* The format is the number of vertices <em>V</em>,
* followed by the number of edges <em>E</em>,
* followed by <em>E</em> pairs of vertices, with each entry separated by whitespace.
Expand All @@ -88,6 +90,7 @@ public Digraph(In in) {
try {
this.V = in.readInt();
if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative");
indegree = new int[V];
adj = (Bag<Integer>[]) new Bag[V];
for (int v = 0; v < V; v++) {
adj[v] = new Bag<Integer>();
Expand All @@ -106,13 +109,15 @@ public Digraph(In in) {
}

/**
* Initializes a new digraph that is a deep copy of <tt>G</tt>.
* Initializes a new digraph that is a deep copy of the specified digraph.
*
* @param G the digraph to copy
*/
public Digraph(Digraph G) {
this(G.V());
this.E = G.E();
for (int v = 0; v < V; v++)
this.indegree[v] = G.indegree(v);
for (int v = 0; v < G.V(); v++) {
// reverse so that adjacency list is in same order as original
Stack<Integer> reverse = new Stack<Integer>();
Expand Down Expand Up @@ -161,6 +166,7 @@ public void addEdge(int v, int w) {
validateVertex(v);
validateVertex(w);
adj[v].add(w);
indegree[w]++;
E++;
}

Expand Down Expand Up @@ -189,6 +195,19 @@ public int outdegree(int v) {
return adj[v].size();
}

/**
* Returns the number of directed edges incident to vertex <tt>v</tt>.
* This is known as the <em>indegree</em> of vertex <tt>v</tt>.
*
* @param v the vertex
* @return the indegree of vertex <tt>v</tt>
* @throws IndexOutOfBoundsException unless 0 <= v < V
*/
public int indegree(int v) {
validateVertex(v);
return indegree[v];
}

/**
* Returns the reverse of the digraph.
*
Expand Down
57 changes: 57 additions & 0 deletions src/main/java/edu/princeton/cs/algs4/DigraphGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,55 @@ public static Digraph cycle(int V) {
return G;
}

/**
* Returns an Eulerian cycle digraph on <tt>V</tt> vertices.
*
* @param V the number of vertices in the cycle
* @param E the number of edges in the cycle
* @return a digraph that is a directed Eulerian cycle on <tt>V</tt> vertices
* and <tt>E</tt> edges
* @throws IllegalArgumentException if either V &le; 0 or E &le; 0
*/
public static Digraph eulerianCycle(int V, int E) {
if (E <= 0)
throw new IllegalArgumentException("An Eulerian cycle must have at least one edge");
if (V <= 0)
throw new IllegalArgumentException("An Eulerian cycle must have at least one vertex");
Digraph G = new Digraph(V);
int[] vertices = new int[E];
for (int i = 0; i < E; i++)
vertices[i] = StdRandom.uniform(V);
for (int i = 0; i < E-1; i++) {
G.addEdge(vertices[i], vertices[i+1]);
}
G.addEdge(vertices[E-1], vertices[0]);
return G;
}

/**
* Returns an Eulerian cycle digraph on <tt>V</tt> vertices.
*
* @param V the number of vertices in the path
* @param E the number of edges in the path
* @return a digraph that is a directed Eulerian path on <tt>V</tt> vertices
* and <tt>E</tt> edges
* @throws IllegalArgumentException if either V &le; 0 or E &lt; 0
*/
public static Digraph eulerianPath(int V, int E) {
if (E < 0)
throw new IllegalArgumentException("negative number of edges");
if (V <= 0)
throw new IllegalArgumentException("An Eulerian path must have at least one vertex");
Digraph G = new Digraph(V);
int[] vertices = new int[E+1];
for (int i = 0; i < E+1; i++)
vertices[i] = StdRandom.uniform(V);
for (int i = 0; i < E; i++) {
G.addEdge(vertices[i], vertices[i+1]);
}
return G;
}

/**
* Returns a random simple digraph on <tt>V</tt> vertices, <tt>E</tt>
* edges and (at least) <tt>c</tt> strong components. The vertices are randomly
Expand Down Expand Up @@ -412,6 +461,14 @@ public static void main(String[] args) {
StdOut.println(cycle(V));
StdOut.println();

StdOut.println("Eulierian path");
StdOut.println(eulerianPath(V, E));
StdOut.println();

StdOut.println("Eulierian cycle");
StdOut.println(eulerianCycle(V, E));
StdOut.println();

StdOut.println("binary tree");
StdOut.println(binaryTree(V));
StdOut.println();
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/edu/princeton/cs/algs4/DirectedCycleX.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,10 @@ public class DirectedCycleX {

public DirectedCycleX(Digraph G) {

// compute indegrees
// indegrees of remaining vertices
int[] indegree = new int[G.V()];
for (int v = 0; v < G.V(); v++) {
for (int w : G.adj(v)) {
indegree[w]++;
}
indegree[v] = G.indegree(v);
}

// initialize queue to contain all vertices with indegree = 0
Expand Down
25 changes: 21 additions & 4 deletions src/main/java/edu/princeton/cs/algs4/EdgeWeightedDigraph.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@
public class EdgeWeightedDigraph {
private static final String NEWLINE = System.getProperty("line.separator");

private final int V;
private int E;
private Bag<DirectedEdge>[] adj;
private final int V; // number of vertices in this digraph
private int E; // number of edges in this digraph
private Bag<DirectedEdge>[] adj; // adj[v] = adjacency list for vertex v
private int[] indegree; // indegree[v] = indegree of vertex v

/**
* Initializes an empty edge-weighted digraph with <tt>V</tt> vertices and 0 edges.
Expand All @@ -49,6 +50,7 @@ public EdgeWeightedDigraph(int V) {
if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative");
this.V = V;
this.E = 0;
this.indegree = new int[V];
adj = (Bag<DirectedEdge>[]) new Bag[V];
for (int v = 0; v < V; v++)
adj[v] = new Bag<DirectedEdge>();
Expand All @@ -75,7 +77,7 @@ public EdgeWeightedDigraph(int V, int E) {
}

/**
* Initializes an edge-weighted digraph from an input stream.
* Initializes an edge-weighted digraph from the specified input stream.
* The format is the number of vertices <em>V</em>,
* followed by the number of edges <em>E</em>,
* followed by <em>E</em> pairs of vertices and edge weights,
Expand Down Expand Up @@ -107,6 +109,8 @@ public EdgeWeightedDigraph(In in) {
public EdgeWeightedDigraph(EdgeWeightedDigraph G) {
this(G.V());
this.E = G.E();
for (int v = 0; v < G.V(); v++)
this.indegree[v] = G.indegree(v);
for (int v = 0; v < G.V(); v++) {
// reverse so that adjacency list is in same order as original
Stack<DirectedEdge> reverse = new Stack<DirectedEdge>();
Expand Down Expand Up @@ -184,6 +188,19 @@ public int outdegree(int v) {
return adj[v].size();
}

/**
* Returns the number of directed edges incident to vertex <tt>v</tt>.
* This is known as the <em>indegree</em> of vertex <tt>v</tt>.
*
* @param v the vertex
* @return the indegree of vertex <tt>v</tt>
* @throws IndexOutOfBoundsException unless 0 <= v < V
*/
public int indegree(int v) {
validateVertex(v);
return indegree[v];
}

/**
* Returns all directed edges in this edge-weighted digraph.
* To iterate over the edges in this edge-weighted digraph, use foreach notation:
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/princeton/cs/algs4/IndexMaxPQ.java
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public void changeKey(int i, Key key) {
* @param i the index of the key to change
* @param key change the key assocated with index <tt>i</tt> to this key
* @throws IndexOutOfBoundsException unless 0 &le; <tt>i</tt> &lt; <tt>maxN</tt>
* @deprecated Replaced by {@link #changeKey(int, Object)}.
* @deprecated Replaced by {@link #changeKey(int, Key)}.
*/
public void change(int i, Key key) {
changeKey(i, key);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/edu/princeton/cs/algs4/IndexMinPQ.java
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public void changeKey(int i, Key key) {
* @param i the index of the key to change
* @param key change the key assocated with index <tt>i</tt> to this key
* @throws IndexOutOfBoundsException unless 0 &le; <tt>i</tt> &lt; <tt>maxN</tt>
* @deprecated Replaced by {@link #changeKey(int,%20Key)}.
* @deprecated Replaced by {@link #changeKey(int, Key)}.
*/
public void change(int i, Key key) {
changeKey(i, key);
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/edu/princeton/cs/algs4/Insertion.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@
* The <tt>Insertion</tt> class provides static methods for sorting an
* array using insertion sort.
* <p>
* This implementation makes ~ 1/2 N^2 compares and exchanges in
* the worst case, so it is not suitable for sorting large arbitrary arrays.
* More precisely, the number of exchanges is exactly equal to the number
* of inversions. So, for example, it sorts a partially-sorted array
* in linear time.
* <p>
* The sorting algorithm is stable and uses O(1) extra memory.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
Expand Down
Loading

0 comments on commit 7108dc6

Please sign in to comment.