Java Algorithms and Clients





Java programming environment. Here are instructions for setting up an IntelliJ-based Java programming environment for Mac OS X, Windows, and Linux.

Design goals. Our original goal for this book was to cover the 50 algorithms that every programmer should know. We use the word programmer to refer to anyone engaged in trying to accomplish something with the help of a computer, including scientists, engineers, and applications developers, not to mention college students in science, engineering, and computer science. The code is optimized for clarity, portability, and efficiency. While some of our implementations are as fast as their counterparts in java.util , our primary goal is to express the core algorithmic idea in an elegant and efficient manner. While we embrace some advanced Java features (such as generics and iterators), we avoid others that would interfere with the exposition (such as inheritance and concurrency).

Algorithms and clients in the textbook. The list below includes nearly 200 Java programs (some are clients, some others are basic infrastructure). Click on the program name to access the Java code; click on the description to access the javadoc; click on the data file names to access the data.











Standard input and output libraries.

We use these standard input and output libraries from Introduction to Programming: An Interdisciplinary Approach. They are part of algs4.jar





Installing the textbook libraries.

IntelliJ. The IntelliJ project folders that we suppply for COS 226 and Coursera are configured to put algs4.jar in the Java classpath.

Mac OS X Terminal (automatic). The Mac OS X installer downloads algs4.jar to the /usr/local/lift folder and provides the wrapper scripts javac-algs4 and java-algs4 , which classpath in algs4.jar , for use in the Terminal.

folder and provides the wrapper scripts and , which classpath in , for use in the Terminal. Windows Git Bash (automatic). The Windows installer downloads algs4.jar to the C:\Program Files\LIFT-CS folder; adds it the Git Bash classpath; and provides the wrapper scripts javac-algs4 and java-algs4 , which classpath in algs4.jar , for use from Git Bash.

folder; adds it the Git Bash classpath; and provides the wrapper scripts and , which classpath in , for use from Git Bash. Windows Command Prompt (manual). Download algs4.jar to a folder, say C:\Users\username\algs4 . Next, add algs4.jar to the CLASSPATH environment variable. Windows 7: Start -> Computer -> System Properties -> Advanced system settings -> Environment Variables -> User variables -> CLASSPATH. Vista: Start -> My Computer -> Properties -> Advanced -> Environment Variables -> User variables -> CLASSPATH. Prepend the following to the beginning of the CLASSPATH variable: C:\Users\username\algs4\algs4.jar; The semicolons separate entries in the CLASSPATH. Click OK three times. If you don't see a variable named CLASSPATH, click New and in the popup window enter CLASSPATH for the variable name. Then, perform the instructions above.

. Next, add to the environment variable. Windows Command Prompt (heavy handed). Download algs4.jar and put it in the directory %SystemRoot%\Sun\Java\lib\ext\ .

. Mac OS X Terminal (manual). Download algs4.jar to a folder, say ~/algs4 . Depending on your shell, add the following line or lines to the file specified: Bourne-again shell (bash). Add the following line to the file ~/.bash_profile (if it exists); otherwise add it to the file ~/.bash_login (if it exists); otherwise, add it to the file ~/.profile (if it doesn't exist, create it first): export CLASSPATH=$CLASSPATH:~/algs4/algs4.jar The colons separate entries in the CLASSPATH. C shell (csh). Add the following line to the file ~/.cshrc (if it doesn't exist, create it first): if ( !($?CLASSPATH) ) then setenv CLASSPATH .:~/algs4/algs4.jar else setenv CLASSPATH .:~/algs4/algs4.jar:${CLASSPATH} endif Bourne shell (sh). Add the following line to the file ~/.profile (if it doesn't exist, create it first): export CLASSPATH=$CLASSPATH:~/algs4/algs4.jar T shell (tcsh). Add the following line to the file ~/.tcshrc (if it exists); otherwise add it to the file ~/.cshrc (if it doesn't exist, create it first): if ( !($?CLASSPATH) ) then setenv CLASSPATH .:~/algs4/algs4.jar else setenv CLASSPATH .:~/algs4/algs4.jar:${CLASSPATH} endif

. Depending on your shell, add the following line or lines to the file specified: Mac OS X (heavy handed). Download algs4.jar and put it in the folder /Users/username/Library/Java/Extensions/ .

. Linux Command Line (manual). Follow the same instructions as for Mac OS X Terminal.

Linux (heavy handed). Download algs4.jar and put it in the directory /usr/java/packages/lib/ext/ .

. DrJava (manual). Download algs4.jar to a folder and add algs4.jar to the classpath via Preferences -> Resources -> Extra Classpath -> Add.

to the classpath via Preferences -> Resources -> Extra Classpath -> Add. Eclipse (manual). Download algs4.jar to a folder and add algs4.jar to the classpath variable to the build path of a project via Project -> Properties -> Java Build Path -> Libaries -> Add External JARs.

To use the textbook libraries, download algs4.jar and it to the classpath. Do not unjar it. Here is how to accomplish that in a variety of environments:

Accessing the textbook libraries.

import

import edu.princeton.cs.algs4.MinPQ; import edu.princeton.cs.algs4.StdIn;

To access the classes in algs4.jar, you will need to usestatements like the ones below:

Download our test data files.

algs4-data

To use the data, unzip algs4-data.zip . It will create a subdirectorywith all of the data files used in the textbook.

Git.

We maintain the source code in a Git repository , suitable for use with Maven or Gradle.

Maven and Gradle.

algs4.jar

We maintainas a Bintray resource , for use with Maven or Gradle.







Exercise solutions.

Here is a list of solutions to selected coding exercises.





1 FUNDAMENTALS 1.2.13 Transaction.java transaction data type 1.2.16 Rational.java rational number data type 1.2.19 Date.java date data type 1.3.1 FixedCapacityStackOfStrings.java add isFull() method to stack 1.3.4 Parentheses.java balanced parentheses 1.3.7 Stack.java add peek() method to stack 1.3.10 InfixToPostfix.java infix-to-postfix conversion 1.3.11 EvaluatePostfix.java evaluate a postfix expression 1.3.14 ResizingArrayQueue.java resizing array queue 1.3.37 Josephus.java Josephus problem 1.4.14 FourSum.java brute-force 4-sum 1.5.7 QuickUnionUF.java quick union 1.5.7 QuickFindUF.java quick find 1.5.17 ErdosRenyi.java Erdos-Renyi simulation 2 SORTING 2.1.1 TraceSelection.java trace of selection sort 2.1.4 TraceInsertion.java trace of insertion sort 2.1.9 TraceShell.java trace of shellsort 2.1.21 Transaction.java add natural order to Transaction 2.1.22 SortTransactions.java sort transactions 2.1.23 InsertionX.java insertion sort with sentinel 2.1.24 InsertionX.java insertion sort with half exchanges 2.2.2 TraceMerge.java mergesort trace 2.2.3 TraceMergeBU.java bottom-up mergesort trace 2.2.9 Merge.java mergesort without static array 2.2.11 MergeX.java improved mergesort 2.2.19 Inversions.java count number of inversions 2.2.20 Merge.java index sort 2.3.1 TracePartition.java partition trace 2.3.2 TraceQuick.java quicksort trace 2.3.5 Sort2distinct.java sort array with 2 distinct keys 2.3.12 TraceQuick3way.java 3-way quicksort trace 2.3.16 QuickBest.java best-case for quicksort 2.3.22 QuickX.java Bentley-McIlroy 3-way quicksort 2.4.3 OrderedArrayMaxPQ.java ordered array priority queue 2.4.3 UnorderedArrayMaxPQ.java unordered array priority queue 2.4.15 MaxPQ.java check if an array is heap-ordered 2.4.25 CubeSum.java find a^3 + b^3 = c^3 + d^3 2.4.33 IndexMaxPQ.java index priority queue 2.5.8 Frequency.java count word frequencies 2.5.12 SPT.java shortest processing time first rule 2.5.13 LPT.java longest processing time first rule 2.5.14 Domain.java sort by reverse domain name 2.5.16 California.java 2003 California gubernatorial election order 2.5.19 KendallTau.java Kendall Tau distance 2.5.24 StableMinPQ.java stable priority queue 2.5.25 Point2D.java point comparators 2.5.27 Insertion.java index sort 2.5.28 FileSorter.java sort files by name 3 SEARCHING 3.1.1 GPA.java compute GPA 3.1.2 ArrayST.java unordered-array symbol table 3.1.5 SequentialSearchST.java add size(), delete(), and keys() 3.1.16 BinarySearchST.java add delete() 3.1.17 BinarySearchST.java add floor() 3.1.29 TestBinarySearchST.java test client 3.1.30 BinarySearchST.java check internal invariants 3.2.6 BST.java add height() method 3.2.10 TestBST.java test client 3.2.13 NonrecursiveBST.java nonrecursive BST 3.2.25 PerfectBalance.java perfectly balanced BST 3.2.32 BST.java order check 3.2.33 BST.java rank/select check 4 GRAPHS 4.1.3 Graph.java add copy constructor 4.1.13 BreadthFirstPaths.java add distTo() method 4.1.23 BaconHistogram.java histogram of Bacon numbers 4.1.26 DegreesOfSeparationDFS.java degrees of separation with DFS 4.1.27 MemoryOfGraph.java memory of Graph data type 4.1.36 Bridge.java find bridges 4.2.3 Digraph.java add copy constructor 4.2.21 MemoryOfDigraph.java memory of Digraph data type 4.2.23 DirectedEulerianCycle.java directed Eulerian cycle 4.2.31 TopologicalX.java queue-based topologial sort 4.2.39 WebCrawler.java web crawler 4.3.9 EdgeWeightedGraph.java edge-weighted graph constructor 4.3.11 MemoryOfEdgeWeightedGraph.java memory of edge-weighted graph 4.3.17 EdgeWeightedGraph.java add toString() to EdgeWeightedGraph 4.3.21 PrimMST.java add edges() to PrimMST 4.3.22 PrimMST.java minimum spanning forest 4.3.22 KruskalMST.java minimum spanning forest 4.3.33 KruskalMST.java MST certification 4.3.43 BoruvkaMST.java Boruvka's algorithm 4.4.2 EdgeWeightedDigraph.java add toString() method 4.4.11 MemoryOfEdgeWeightedDigraph.java memory of EdgeWeightedDigraph data type 4.4.12 Topological.java topological sort in edge-weighted digraphs 4.4.12 EdgeWeightedDirectedCycle.java directed cycle in edge-weighted digraphs 4.4.28 AcyclicLP.java longest paths in DAGs 4.4.35 LazyDijkstraSP.java lazy implementation of Dijkstra





Q + A



Q. What is the easiest way to execute the main() method in classes that are contained in algs4.jar ?

A. If you used our autoinstaller, you can execute with a command like

% java-algs4 edu.princeton.cs.algs4.StdDraw

Q. Can I use algs4.jar in my project?

A. The library algs4.jar is released under the GNU General Public License, version 3 (GPLv3). If you wish to license the code under different terms, please contact us to discuss.

Q. There are some classic algorithms missing from your library. Can I help you add more?

A. Here are a few algorithms on our wishlist. If you wish to implement any of these and contribute to algs4.jar, send us an email and we'd be happy to include your code with an appropriate attribution. Be sure to thoroughly test and comment your code; strive for clarity; and use a style consistent with the other programs in the library.



