전체 페이지뷰

2017년 5월 7일 일요일

java algorithms and data structure


http://algs4.cs.princeton.edu/code/

Java Algorithms and Clients


As of August 17, 2015, the "default package" version of algs4.jar has been replaced with a "named package" version. To access the classes in algs4.jar, you will need to use an import statement like the ones below:
import edu.princeton.cs.algs4.MinPQ;
import edu.princeton.cs.algs4.StdIn;
Note that the I/O libraries from stdlib.jar are now contained in algs4.jar, so you no longer need stdlib.jar.

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 the corresponding counterparts in java.util, our 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. You can download all of the programs as algs4.jar and the data as algs4-data.zip.

1FUNDAMENTALS
BinarySearch.javabinary search
RandomSeq.javarandom numbers in a given range
Average.javaaverage of a sequence of numbers
Cat.javaconcatenate files
Knuth.javaKnuth shuffle
Counter.javacounter
StaticSETofInts.javaset of integers
Whitelist.javawhitelist client
Vector.javaEuclidean vector
Date.javadate
Transaction.javatransaction
Point2D.javapoint
RectHV.javaaxis-aligned rectangle
Interval1D.java1d interval
Interval2D.java2d interval
Accumulator.javarunning average and stddev
1.1ResizingArrayStack.javaLIFO stack (resizing array)
1.2LinkedStack.javaLIFO stack (linked list)
Stack.javaLIFO stack
ResizingArrayQueue.javaFIFO queue (resizing array)
1.3LinkedQueue.javaFIFO queue (linked list)
Queue.javaFIFO queue
ResizingArrayBag.javamultiset (resizing array)
1.4LinkedBag.javamultiset (linked list)
Bag.javamultiset
Stopwatch.javatimer (wall time)
StopwatchCPU.javatimer (CPU time)
LinearRegression.javasimple linear regression
ThreeSum.javabrute-force three sum
ThreeSumFast.javafaster three sum
DoublingTest.javadoubling test
DoublingRatio.javadoubling ratio
QuickFindUF.javaquick find
QuickUnionUF.javaquick union
1.5WeightedQuickUnionUF.javaweighted quick union
UF.javaunion-by-rank with path halving
2SORTING
2.1Insertion.javainsertion sort
InsertionX.javainsertion sort (optimized)
BinaryInsertion.javabinary insertion sort
2.2Selection.javaselection sort
2.3Shell.javashellsort
2.4Merge.javatop-down mergesort
MergeBU.javabottom-up mergesort
MergeX.javaoptimized mergesort
2.5Quick.javaquicksort
Quick3way.javaquicksort with 3-way partitioning
QuickX.javaoptimized quicksort
TopM.javapriority queue client
2.6MaxPQ.javamax heap priority queue
MinPQ.javamin heap priority queue
IndexMinPQ.javaindex min heap priority queue
IndexMaxPQ.javaindex max heap priority queue
Multiway.javamultiway merge
2.7Heap.javaheapsort
3SEARCHING
FrequencyCounter.javafrequency counter
3.1SequentialSearchST.javasequential search
3.2BinarySearchST.javabinary search
3.3BST.javabinary search tree
3.4RedBlackBST.javared-black tree
3.5SeparateChainingHashST.javaseparate chaining hash table
3.6LinearProbingHashST.javalinear probing hash table
ST.javaordered symbol table
SET.javaordered set
DeDup.javaremove duplicates
WhiteFilter.javawhitelist filter
BlackFilter.javablacklist filter
LookupCSV.javadictionary lookup
LookupIndex.javaindex and inverted index
FileIndex.javafile indexing
SparseVector.javasparse vector
4GRAPHS
Graph.javaundirected graph
GraphGenerator.javagenerate random graphs
DepthFirstSearch.javadepth-first search in a graph
NonrecursiveDFS.javaDFS in a graph (nonrecursive)
4.1DepthFirstPaths.javapaths in a graph (DFS)
4.2BreadthFirstPaths.javapaths in a graph (BFS)
4.3CC.javaconnected components of a graph
Bipartite.javabipartite or odd cycle (DFS)
BipartiteX.javabipartite or odd cycle (BFS)
Cycle.javacycle in a graph
EulerianCycle.javaEulerian cycle in a graph
EulerianPath.javaEulerian path in a graph
SymbolGraph.javasymbol graph
DegreesOfSeparation.javadegrees of separation
Digraph.javadirected graph
DigraphGenerator.javagenerate random digraphs
4.4DirectedDFS.javadepth-first search in a digraph
NonrecursiveDirectedDFS.javaDFS in a digraph (nonrecursive)
DepthFirstDirectedPaths.javapaths in a digraph (DFS)
BreadthFirstDirectedPaths.javapaths in a digraph (BFS)
DirectedCycle.javacycle in a digraph
DirectedCycleX.javacycle in a digraph (nonrecursive)
DirectedEulerianCycle.javaEulerian cycle in a digraph
DirectedEulerianPath.javaEulerian path in a digraph
DepthFirstOrder.javadepth-first order in a digraph
4.5Topological.javatopological order in a DAG
TopologicalX.javatopological order (nonrecursive)
TransitiveClosure.javatransitive closure
SymbolDigraph.javasymbol digraph
4.6KosarajuSharirSCC.javastrong components (Kosaraju–Sharir)
TarjanSCC.javastrong components (Tarjan)
GabowSCC.javastrong components (Gabow)
EdgeWeightedGraph.javaedge-weighted graph
Edge.javaweighted edge
LazyPrimMST.javaMST (lazy Prim)
4.7PrimMST.javaMST (Prim)
4.8KruskalMST.javaMST (Kruskal)
BoruvkaMST.javaMST (Boruvka)
EdgeWeightedDigraph.javaedge-weighted digraph
DirectedEdge.javaweighted, directed edge
4.9DijkstraSP.javashortest paths (Dijkstra)
DijkstraUndirectedSP.javaundirected shortest paths (Dijkstra)
DijkstraAllPairsSP.javaall-pairs shortest paths
4.10AcyclicSP.javashortest paths in a DAG
AcyclicLP.javalongest paths in a DAG
CPM.javacritical path method
4.11BellmanFordSP.javashortest paths (Bellman–Ford)
EdgeWeightedDirectedCycle.javacycle in an edge-weighted digraph
Arbitrage.javaarbitrage detection
FloydWarshall.javaall-pairs shortest paths (dense)
AdjMatrixEdgeWeightedDigraph.javaedge-weighted graph (dense)
5STRINGS
Alphabet.javaalphabet
Count.javaalphabet client
5.1LSD.javaLSD radix sort
5.2MSD.javaMSD radix sort
5.3Quick3string.java3-way string quicksort
5.4TrieST.javamultiway trie symbol table
TrieSET.javamultiway trie set
5.5TST.javaternary search trie
5.6KMP.javasubstring search (Knuth–Morris–Pratt)
5.7BoyerMoore.javasubstring search (Boyer–Moore)
5.8RabinKarp.javasubstring search (Rabin–Karp)
5.9NFA.javaNFA for regular expressions
GREP.javagrep
BinaryDump.javabinary dump
HexDump.javahex dump
PictureDump.javapicture dump
Genome.javagenomic code
RunLength.javadata compression (run-length coding)
5.10Huffman.javadata compression (Huffman)
5.11LZW.javadata compression (Lempel–Ziv–Welch)
6CONTEXT
6.1CollisionSystem.javacollision system
Particle.javaparticle
6.2BTree.javaB-tree
6.3SuffixArray.javasuffix array (suffix sorting)
SuffixArrayX.javasuffix array (optimized)
LongestRepeatedSubstring.javalongest repeated substring
KWIK.javakeyword in context
LongestCommonSubstring.javalongest common substring
6.4FordFulkerson.javamaxflow–mincut
FlowNetwork.javacapacitated network
FlowEdge.javacapacitated edge with flow
GlobalMincut.javaglobal mincut (Stoer–Wagner)4
BipartiteMatching.javabipartite matching (alternating path)
HopcroftKarp.javabipartite matching (Hopcroft–Karp)
AssignmentProblem.javaweighted bipartite matching
LinearProgramming.javalinear programming (simplex)
TwoPersonZeroSumGame.javatwo-person zero-sum game
9BEYOND
GaussianElimination.javaGaussian elimination
GaussJordanElimination.javaGauss–Jordan elimination
FFT.javaFast Fourier transform
Complex.javacomplex number
GrahamScan.java2d convex hull (Graham scan)
FarthestPair.java2d farthest pair (rotating calipers)
ClosestPair.java2d closest pair
FenwickTree.javaFenwich tree1
SegmentTree.javaSegment tree1
PatriciaST.javaPATRICIA trie symbol table2
PatriciaSET.javaPATRICIA trie set2
MultiwayMinPQ.javaMultiway heap3
IndexMultiwayMinPQ.javaIndex multiway heap3
BinomialMinPQ.javaBinomial heap3
IndexBinomialMinPQ.javaIndex binomial heap3
FibonacciMinPQ.javaFibonacci heap3
IndexFibonacciMinPQ.javaIndex Fibonacci heap3
AVLTreeST.javaAVL tree4
1 contributed by Ricardo Pacheco
2 contributed by John Hentosh
3 contributed by Tristan Claverie
4 contributed by Marcelo Silva

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.

§PROGRAMDESCRIPTION / JAVADOC
1.5StdIn.javaread numbers and text from standard input
1.5StdOut.javawrite numbers and text to standard output
1.5StdDraw.javadraw geometric shapes in a window
1.5StdAudio.javacreate, play, and manipulate sound
2.2StdRandom.javagenerate random numbers
2.2StdStats.javacompute statistics
2.2StdArrayIO.javaread and write 1D and 2D arrays
3.1In.javaread numbers and text from files and URLs
3.1Out.javawrite numbers and text to files
3.1Draw.javadraw geometric shapes
3.1DrawListener.javainteractions with Draw
3.1Picture.javaprocess digital images
BinaryStdIn.javaread bits from standard input
BinaryStdOut.javawrite bits to standard output
BinaryIn.javaread bits from files and URLs
BinaryOut.javawrite bits to files

Installing Java.

 Here are instructions for installing a Java programming environment on your operating system: Mac OS XWindows, or Linux.

Installing the textbook libraries.

 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:
  • Mac OS X (automatic). The Mac OS X installer downloads algs4.jar to the /Users/username/algs4 folder; adds it to the DrJava classpath; and provides the wrapper scripts javac-algs4 and java-algs4, which classpath in algs4.jar, for use in the Terminal.
  • Windows (automatic). The Windows installer downloads algs4.jar to the C:\Users\username\algs4 folder; adds it the DrJava classpath; and provides the wrapper scripts javac-algs4 and java-algs4, which classpath in algs4.jar, for use from the Command Prompt.
  • 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.
      Windows XP: Start -> Control Panel -> System -> 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.
  • 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
      
  • 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 algs4.jar 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.

Download our test data files.

 To use the data, unzip algs4-data.zip. It will create a subdirectory algs4-data with 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.

Exercise solutions.

 Here is a list of solutions to selected coding exercises.

1FUNDAMENTALS
1.2.13Transaction.javatransaction data type
1.2.16Rational.javarational number data type
1.2.19Date.javadate data type
1.3.1FixedCapacityStackOfStrings.javaadd isFull() method to stack
1.3.4Parentheses.javabalanced parentheses
1.3.7Stack.javaadd peek() method to stack
1.3.10InfixToPostfix.javainfix-to-postfix conversion
1.3.11EvaluatePostfix.javaevaluate a postfix expression
1.3.14ResizingArrayQueue.javaresizing array queue
1.3.37Josephus.javaJosephus problem
1.4.14FourSum.javabrute-force 4-sum
1.5.7QuickUnionUF.javaquick union
1.5.7QuickFindUF.javaquick find
1.5.17ErdosRenyi.javaErdos-Renyi simulation
2SORTING
2.1.1TraceSelection.javatrace of selection sort
2.1.4TraceInsertion.javatrace of insertion sort
2.1.9TraceShell.javatrace of shellsort
2.1.21Transaction.javaadd natural order to Transaction
2.1.22SortTransactions.javasort transactions
2.1.23InsertionX.javainsertion sort with sentinel
2.1.24InsertionX.javainsertion sort with half exchanges
2.2.2TraceMerge.javamergesort trace
2.2.3TraceMergeBU.javabottom-up mergesort trace
2.2.9Merge.javamergesort without static array
2.2.11MergeX.javaimproved mergesort
2.2.19Inversions.javacount number of inversions
2.2.20Merge.javaindex sort
2.3.1TracePartition.javapartition trace
2.3.2TraceQuick.javaquicksort trace
2.3.5Sort2distinct.javasort array with 2 distinct keys
2.3.12TraceQuick3way.java3-way quicksort trace
2.3.16QuickBest.javabest-case for quicksort
2.3.22QuickX.javaBentley-McIlroy 3-way quicksort
2.4.3OrderedArrayMaxPQ.javaordered array priority queue
2.4.3UnorderedArrayMaxPQ.javaunordered array priority queue
2.4.15MaxPQ.javacheck if an array is heap-ordered
2.4.25CubeSum.javafind a^3 + b^3 = c^3 + d^3
2.4.33IndexMaxPQ.javaindex priority queue
2.5.8Frequency.javacount word frequencies
2.5.12SPT.javashortest processing time first rule
2.5.13LPT.javalongest processing time first rule
2.5.14Domain.javasort by reverse domain name
2.5.16California.java2003 California gubernatorial election order
2.5.19KendallTau.javaKendall Tau distance
2.5.24StableMinPQ.javastable priority queue
2.5.25Point2D.javapoint comparators
2.5.27Insertion.javaindex sort
2.5.28FileSorter.javasort files by name
3SEARCHING
3.1.1GPA.javacompute GPA
3.1.2ArrayST.javaunordered-array symbol table
3.1.5SequentialSearchST.javaadd size(), delete(), and keys()
3.1.16BinarySearchST.javaadd delete()
3.1.17BinarySearchST.javaadd floor()
3.1.29TestBinarySearchST.javatest client
3.1.30BinarySearchST.javacheck internal invariants
3.2.6BST.javaadd height() method
3.2.10TestBST.javatest client
3.2.13NonrecursiveBST.javanonrecursive BST
3.2.25PerfectBalance.javaperfectly balanced BST
3.2.32BST.javaorder check
3.2.33BST.javarank/select check
4GRAPHS
4.1.3Graph.javaadd copy constructor
4.1.13BreadthFirstPaths.javaadd distTo() method
4.1.23BaconHistogram.javahistogram of Bacon numbers
4.1.26DegreesOfSeparationDFS.javadegrees of separation with DFS
4.1.27MemoryOfGraph.javamemory of Graph data type
4.1.36Bridge.javafind bridges
4.2.3Digraph.javaadd copy constructor
4.2.21MemoryOfDigraph.javamemory of Digraph data type
4.2.23DirectedEulerianCycle.javadirected Eulerian cycle
4.2.31TopologicalX.javaqueue-based topologial sort
4.2.39WebCrawler.javaweb crawler
4.3.9EdgeWeightedGraph.javaedge-weighted graph constructor
4.3.11MemoryOfEdgeWeightedGraph.javamemory of edge-weighted graph
4.3.17EdgeWeightedGraph.javaadd toString() to EdgeWeightedGraph
4.3.21PrimMST.javaadd edges() to PrimMST
4.3.22PrimMST.javaminimum spanning forest
4.3.22KruskalMST.javaminimum spanning forest
4.3.33KruskalMST.javaMST certification
4.3.43BoruvkaMST.javaBoruvka's algorithm
4.4.2EdgeWeightedDigraph.javaadd toString() method
4.4.11MemoryOfEdgeWeightedDigraph.javamemory of EdgeWeightedDigraph data type
4.4.12Topological.javatopological sort in edge-weighted digraphs
4.4.12EdgeWeightedDirectedCycle.javadirected cycle in edge-weighted digraphs
4.4.28AcyclicLP.javalongest paths in DAGs
4.4.35LazyDijkstraSP.javalazy 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 your code 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 our publisher to discuss.
Q. There are some classic algorithms missing from your library. Can I help you add more?
A. Here 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.

댓글 없음:

댓글 쓰기