├── data.txt ├── readme.txt ├── src ├── UF.java ├── Queue.java ├── graph │ ├── Cycle.java │ ├── TwoColor.java │ ├── Topological.java │ ├── DepthFirstSearch.java │ ├── DepthFirstOrder.java │ ├── Digraph.java │ ├── CC.java │ ├── DirectedCycle.java │ ├── DepthFirstPaths.java │ ├── DirectedDFS.java │ ├── BreadthFirstPaths.java │ ├── KosarajuSCC.java │ ├── Graph.java │ └── SymbolGraph.java ├── sort │ ├── Example.java │ ├── Data.java │ ├── SortCompare.java │ └── MaxPQ.java ├── graph2 │ ├── AcyclicSP.java │ ├── DijkstraSP.java │ ├── CPM.java │ ├── DijkstraAllPairsSP.java │ ├── MST.java │ ├── Edge.java │ └── EdgeWeightedGraph.java ├── st │ ├── LinearProbingHashST.java │ ├── brst.java │ ├── ST.java │ ├── SequentialSearchST.java │ ├── BinarySearchST.java │ └── BST.java ├── Stats.java ├── hello.java ├── DoublingRatio.java ├── StopWatch.java ├── stack.java ├── ResizingArrayStack.java └── WeightedQuickUnionPathHalvingUF.java ├── bin ├── UF.class ├── Queue.class ├── Stats.class ├── hello.class ├── st │ ├── BST.class │ ├── brst.class │ ├── BST$Node.class │ ├── brst$Node.class │ ├── BinarySearchST.class │ ├── SequentialSearchST.class │ ├── LinearProbingHashST.class │ └── SequentialSearchST$Node.class ├── stack.class ├── graph │ ├── CC.class │ ├── Cycle.class │ ├── Graph.class │ ├── Digraph.class │ ├── TwoColor.class │ ├── DirectedDFS.class │ ├── KosarajuSCC.class │ ├── SymbolGraph.class │ ├── Topological.class │ ├── DepthFirstOrder.class │ ├── DepthFirstPaths.class │ ├── DirectedCycle.class │ ├── BreadthFirstPaths.class │ └── DepthFirstSearch.class ├── Queue$Node.class ├── StopWatch.class ├── graph2 │ ├── CPM.class │ ├── Edge.class │ ├── MST.class │ ├── AcyclicSP.class │ ├── DijkstraSP.class │ ├── DijkstraAllPairsSP.class │ └── EdgeWeightedGraph.class ├── sort │ ├── Data.class │ ├── MaxPQ.class │ ├── Example.class │ └── SortCompare.class ├── stack$Node.class ├── DoublingRatio.class ├── Queue$Listiterator.class ├── ResizingArrayStack.class ├── stack$ListIterator.class ├── WeightedQuickUnionPathHalvingUF.class └── ResizingArrayStack$ReverseArrayIterator.class ├── tinyG.txt ├── tinyDG2.txt ├── tinyEDG.txt ├── tinyDG.txt ├── .classpath ├── .project └── .settings └── org.eclipse.jdt.core.prefs /data.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | -1 6 | -3 7 | -4 8 | -5 -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/readme.txt -------------------------------------------------------------------------------- /src/UF.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/src/UF.java -------------------------------------------------------------------------------- /bin/UF.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/UF.class -------------------------------------------------------------------------------- /bin/Queue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/Queue.class -------------------------------------------------------------------------------- /bin/Stats.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/Stats.class -------------------------------------------------------------------------------- /bin/hello.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/hello.class -------------------------------------------------------------------------------- /bin/st/BST.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/BST.class -------------------------------------------------------------------------------- /bin/stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/stack.class -------------------------------------------------------------------------------- /src/Queue.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/src/Queue.java -------------------------------------------------------------------------------- /bin/graph/CC.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/CC.class -------------------------------------------------------------------------------- /bin/st/brst.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/brst.class -------------------------------------------------------------------------------- /bin/Queue$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/Queue$Node.class -------------------------------------------------------------------------------- /bin/StopWatch.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/StopWatch.class -------------------------------------------------------------------------------- /bin/graph/Cycle.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/Cycle.class -------------------------------------------------------------------------------- /bin/graph/Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/Graph.class -------------------------------------------------------------------------------- /bin/graph2/CPM.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph2/CPM.class -------------------------------------------------------------------------------- /bin/graph2/Edge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph2/Edge.class -------------------------------------------------------------------------------- /bin/graph2/MST.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph2/MST.class -------------------------------------------------------------------------------- /bin/sort/Data.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/sort/Data.class -------------------------------------------------------------------------------- /bin/sort/MaxPQ.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/sort/MaxPQ.class -------------------------------------------------------------------------------- /bin/st/BST$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/BST$Node.class -------------------------------------------------------------------------------- /bin/stack$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/stack$Node.class -------------------------------------------------------------------------------- /src/graph/Cycle.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/src/graph/Cycle.java -------------------------------------------------------------------------------- /src/sort/Example.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/src/sort/Example.java -------------------------------------------------------------------------------- /bin/DoublingRatio.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/DoublingRatio.class -------------------------------------------------------------------------------- /bin/graph/Digraph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/Digraph.class -------------------------------------------------------------------------------- /bin/sort/Example.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/sort/Example.class -------------------------------------------------------------------------------- /bin/st/brst$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/brst$Node.class -------------------------------------------------------------------------------- /bin/graph/TwoColor.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/TwoColor.class -------------------------------------------------------------------------------- /bin/graph2/AcyclicSP.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph2/AcyclicSP.class -------------------------------------------------------------------------------- /bin/sort/SortCompare.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/sort/SortCompare.class -------------------------------------------------------------------------------- /src/graph2/AcyclicSP.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/src/graph2/AcyclicSP.java -------------------------------------------------------------------------------- /src/graph2/DijkstraSP.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/src/graph2/DijkstraSP.java -------------------------------------------------------------------------------- /bin/Queue$Listiterator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/Queue$Listiterator.class -------------------------------------------------------------------------------- /bin/ResizingArrayStack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/ResizingArrayStack.class -------------------------------------------------------------------------------- /bin/graph/DirectedDFS.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/DirectedDFS.class -------------------------------------------------------------------------------- /bin/graph/KosarajuSCC.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/KosarajuSCC.class -------------------------------------------------------------------------------- /bin/graph/SymbolGraph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/SymbolGraph.class -------------------------------------------------------------------------------- /bin/graph/Topological.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/Topological.class -------------------------------------------------------------------------------- /bin/graph2/DijkstraSP.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph2/DijkstraSP.class -------------------------------------------------------------------------------- /bin/st/BinarySearchST.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/BinarySearchST.class -------------------------------------------------------------------------------- /bin/stack$ListIterator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/stack$ListIterator.class -------------------------------------------------------------------------------- /bin/graph/DepthFirstOrder.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/DepthFirstOrder.class -------------------------------------------------------------------------------- /bin/graph/DepthFirstPaths.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/DepthFirstPaths.class -------------------------------------------------------------------------------- /bin/graph/DirectedCycle.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/DirectedCycle.class -------------------------------------------------------------------------------- /bin/st/SequentialSearchST.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/SequentialSearchST.class -------------------------------------------------------------------------------- /bin/graph/BreadthFirstPaths.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/BreadthFirstPaths.class -------------------------------------------------------------------------------- /bin/graph/DepthFirstSearch.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph/DepthFirstSearch.class -------------------------------------------------------------------------------- /bin/st/LinearProbingHashST.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/LinearProbingHashST.class -------------------------------------------------------------------------------- /bin/graph2/DijkstraAllPairsSP.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph2/DijkstraAllPairsSP.class -------------------------------------------------------------------------------- /bin/graph2/EdgeWeightedGraph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/graph2/EdgeWeightedGraph.class -------------------------------------------------------------------------------- /bin/st/SequentialSearchST$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/st/SequentialSearchST$Node.class -------------------------------------------------------------------------------- /tinyG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 13 3 | 0 5 4 | 4 3 5 | 0 1 6 | 9 12 7 | 6 4 8 | 5 4 9 | 0 2 10 | 11 12 11 | 9 10 12 | 0 6 13 | 7 8 14 | 9 11 15 | 5 3 -------------------------------------------------------------------------------- /bin/WeightedQuickUnionPathHalvingUF.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/WeightedQuickUnionPathHalvingUF.class -------------------------------------------------------------------------------- /tinyDG2.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 15 3 | 0 1 4 | 0 6 5 | 0 5 6 | 2 0 7 | 2 3 8 | 3 5 9 | 5 4 10 | 6 4 11 | 8 7 12 | 7 6 13 | 6 9 14 | 9 10 15 | 9 11 16 | 9 12 17 | 11 12 -------------------------------------------------------------------------------- /bin/ResizingArrayStack$ReverseArrayIterator.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jocelynthink/stduy_alog_java/master/bin/ResizingArrayStack$ReverseArrayIterator.class -------------------------------------------------------------------------------- /tinyEDG.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 15 3 | 4 5 0.35 4 | 5 4 0.35 5 | 4 7 0.37 6 | 5 7 0.28 7 | 7 5 0.28 8 | 5 1 0.32 9 | 0 4 0.38 10 | 0 2 0.26 11 | 7 3 0.39 12 | 1 3 0.29 13 | 2 7 0.34 14 | 6 2 0.40 15 | 3 6 0.52 16 | 6 0 0.58 17 | 6 4 0.93 -------------------------------------------------------------------------------- /src/graph2/CPM.java: -------------------------------------------------------------------------------- 1 | package graph2; 2 | 3 | public class CPM { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /tinyDG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 22 3 | 4 2 4 | 2 3 5 | 3 2 6 | 6 0 7 | 0 1 8 | 2 0 9 | 11 12 10 | 12 9 11 | 9 10 12 | 9 11 13 | 7 9 14 | 10 12 15 | 11 4 16 | 4 3 17 | 3 5 18 | 6 8 19 | 8 6 20 | 5 4 21 | 0 5 22 | 6 4 23 | 6 9 24 | 7 6 -------------------------------------------------------------------------------- /src/st/LinearProbingHashST.java: -------------------------------------------------------------------------------- 1 | package st; 2 | 3 | public class LinearProbingHashST{ 4 | private int N; 5 | private int M = 16; 6 | private Key[] keys; 7 | private Value[] vals; 8 | 9 | 10 | public static void main(String[] args) { 11 | 12 | 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | algo4 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Stats.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | import edu.princeton.cs.algs4.StdIn; 4 | import edu.princeton.cs.algs4.StdOut; 5 | public class Stats { 6 | 7 | /** 8 | * @param args 9 | */ 10 | public static void main(String[] args) { 11 | // TODO Auto-generated method stub 12 | // Bag numbers = new Bag(); 13 | // Queue a = new Queue(); 14 | Stack stack; 15 | stack = new Stack(); 16 | while(!StdIn.isEmpty()) 17 | stack.push(StdIn.readInt()); 18 | while(!stack.empty()){ 19 | int i = stack.pop(); 20 | StdOut.println(i); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/graph2/DijkstraAllPairsSP.java: -------------------------------------------------------------------------------- 1 | package graph2; 2 | 3 | import edu.princeton.cs.algs4.DirectedEdge; 4 | import edu.princeton.cs.algs4.EdgeWeightedDigraph; 5 | 6 | public class DijkstraAllPairsSP { 7 | 8 | private DijkstraSP[] all; 9 | DijkstraAllPairsSP(EdgeWeightedDigraph G){ 10 | all = new DijkstraSP[G.V()]; 11 | for(int v = 0; v < G.V();v++){ 12 | all[v] = new DijkstraSP(G,v); 13 | } 14 | } 15 | Iterable path(int s,int v){ 16 | return all[s].pathTo(v); 17 | } 18 | double dist(int s,int t){ 19 | return all[s].distTo(t); 20 | } 21 | public static void main(String[] args) { 22 | // TODO Auto-generated method stub 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | #Fri Feb 26 11:36:45 CST 2016 2 | eclipse.preferences.version=1 3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.compliance=1.7 7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.source=1.7 13 | -------------------------------------------------------------------------------- /src/st/brst.java: -------------------------------------------------------------------------------- 1 | package st; 2 | 3 | public class brst,Value> { 4 | 5 | private static final boolean RED = true; 6 | private static final boolean BLACK = false; 7 | 8 | private class Node{ 9 | Key key; 10 | Value val; 11 | Node left,right; 12 | int N; 13 | boolean color; 14 | 15 | Node(Key key,Value val,int N,boolean color){ 16 | this.key = key; 17 | this.val = val; 18 | this.N = N; 19 | this.color = color; 20 | } 21 | } 22 | 23 | private boolean isRed(Node h){ 24 | if(h==null) 25 | return false; 26 | return h.color==RED; 27 | } 28 | public static void main(String[] args) { 29 | // TODO Auto-generated method stub 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/graph/TwoColor.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | public class TwoColor { 4 | 5 | private boolean[] marked; 6 | private boolean[] color; 7 | private boolean isTwoColorable = true; 8 | public TwoColor(Graph G){ 9 | marked = new boolean[G.V()]; 10 | color = new boolean[G.V()]; 11 | for(int s = 0;s mst; 10 | private MinPQ pq; 11 | public void lazyPrimMST(EdgeWeightedGraph G){ 12 | pq = new MinPQ(); 13 | marked = new boolean[G.V()]; 14 | mst = new Queue(); 15 | visit(G,0); 16 | 17 | } 18 | private void visit(EdgeWeightedGraph G, int i) { 19 | 20 | 21 | } 22 | public MST(EdgeWeightedGraph G){ 23 | 24 | } 25 | 26 | public Iterable edges(){ 27 | return mst; 28 | } 29 | public double weight(){ 30 | double weight = 0; 31 | return weight; 32 | } 33 | 34 | public static void main(String[] args) { 35 | // TODO Auto-generated method stub 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/graph2/Edge.java: -------------------------------------------------------------------------------- 1 | package graph2; 2 | 3 | public class Edge implements Comparable { 4 | private final int v; 5 | private final int w; 6 | private final double weight; 7 | 8 | public Edge(int v,int w,double weight){ 9 | this.v = v; 10 | this.w = w; 11 | this.weight = weight; 12 | } 13 | public double weight(){ 14 | return weight; 15 | } 16 | public int either(){ 17 | return v; 18 | } 19 | public int other(int vertex){ 20 | if(vertex == v) 21 | return w; 22 | else if(vertex == w) 23 | return v; 24 | else 25 | throw new RuntimeException("Inconsistent edge"); 26 | } 27 | public int compareTo(Edge that){ 28 | if(this.weight() that.weight()) 31 | return +1; 32 | else{ 33 | return 0; 34 | } 35 | } 36 | public String toString(){ 37 | return String.format("%d-%d %.2f",v,w,weight ); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/sort/Data.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | public class Data implements Comparable { 4 | private final int day; 5 | private final int month; 6 | private final int year; 7 | 8 | public Data(int d,int m,int y){ 9 | day = d; 10 | month = m; 11 | year = y; 12 | } 13 | 14 | public int day(){ 15 | return day; 16 | } 17 | 18 | public int month(){ 19 | return month; 20 | } 21 | public int year(){ 22 | return year; 23 | } 24 | 25 | 26 | public int compareTo(Data that){ 27 | if(this.year > that.year) 28 | return +1; 29 | if(this.year < that.year) 30 | return -1; 31 | if(this.month > that.month) 32 | return +1; 33 | if(this.month< that.month) 34 | return -1; 35 | if(this.day > that.day) 36 | return +1; 37 | if(this.day < that.day) 38 | return -1; 39 | return 0; 40 | } 41 | 42 | public String toString(){ 43 | return month + "/" + day + "/" + year; 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/graph/Topological.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.StdOut; 5 | import edu.princeton.cs.algs4.SymbolDigraph; 6 | 7 | public class Topological { 8 | 9 | private Iterable order; 10 | public Topological(Digraph G){ 11 | DirectedCycle cyclefinder = new DirectedCycle(G); 12 | if(!cyclefinder.hasCycle()){ 13 | DepthFirstOrder dfs = new DepthFirstOrder(G); 14 | order = dfs.reversePost(); 15 | } 16 | } 17 | 18 | public Iterable order(){ 19 | return order; 20 | } 21 | public boolean isDAG(){ 22 | return order != null; 23 | } 24 | public static void main(String[] args) { 25 | In in = new In(args[0]); 26 | Digraph G = new Digraph( in); 27 | Topological top = new Topological(G); 28 | if(top.isDAG()){ 29 | for(int v : top.order()) 30 | StdOut.println(v); 31 | }else{ 32 | StdOut.println("not DAG"); 33 | } 34 | 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/st/ST.java: -------------------------------------------------------------------------------- 1 | //package st; 2 | // 3 | //import edu.princeton.cs.algs4.StdIn; 4 | //import edu.princeton.cs.algs4.StdOut; 5 | // 6 | //public class ST { 7 | // 8 | // public ST(){ 9 | // 10 | // } 11 | // public void put(Key key,Value val){ 12 | // 13 | // } 14 | // public Value get(Key key){ 15 | // 16 | // } 17 | // public void delete(Key key){ 18 | // 19 | // } 20 | // public boolean contains(Key key){ 21 | // 22 | // } 23 | // public boolean isEmpty(){ 24 | // 25 | // } 26 | // public int size(){ 27 | // 28 | // } 29 | // public Iterable keys(){ 30 | // 31 | // } 32 | // 33 | // public static void main(String[] args){ 34 | // ST st; 35 | // st = new ST(); 36 | // 37 | // for(int i = 0; !StdIn.isEmpty();i++){ 38 | // String key = StdIn.readString(); 39 | // st.put(key, i); 40 | // } 41 | // 42 | // for(String s : st.keys()){ 43 | // StdOut.println(s + " " + st.get(s)); 44 | // } 45 | // } 46 | //} 47 | -------------------------------------------------------------------------------- /src/hello.java: -------------------------------------------------------------------------------- 1 | import edu.princeton.cs.algs4.StdDraw; 2 | public class hello { 3 | public static void main(String[] args){ 4 | StdDraw.setScale(-1, 1); 5 | StdDraw.clear(StdDraw.BLACK); 6 | 7 | StdDraw.setPenColor(StdDraw.WHITE); 8 | StdDraw.square(0, 0, 1); 9 | 10 | // write some text 11 | StdDraw.setPenColor(StdDraw.WHITE); 12 | StdDraw.text(0, +0.95, "Hello, world! This is a test Java program."); 13 | StdDraw.text(0, -0.95, "Close this window to finish the installation."); 14 | 15 | // draw the bullseye 16 | StdDraw.setPenColor(StdDraw.BOOK_BLUE); 17 | StdDraw.filledCircle(0, 0, 0.9); 18 | StdDraw.setPenColor(StdDraw.BLACK); 19 | StdDraw.filledCircle(0, 0, 0.8); 20 | StdDraw.setPenColor(StdDraw.BOOK_BLUE); 21 | StdDraw.filledCircle(0, 0, 0.7); 22 | StdDraw.setPenColor(StdDraw.BLACK); 23 | StdDraw.filledCircle(0, 0, 0.6); 24 | 25 | // draw a picture of the textbook 26 | StdDraw.picture(0, 0, "cover.jpg", 0.65, 0.80); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/DoublingRatio.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import edu.princeton.cs.algs4.BinarySearch; 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.StdOut; 5 | public class DoublingRatio { 6 | 7 | public static int count(int[] a){ 8 | Arrays.sort(a); 9 | int N = a.length; 10 | int cnt = 0; 11 | for(int i = 0;i < N;i ++){ 12 | if(BinarySearch.rank(-a[i], a) > i) 13 | cnt ++; 14 | } 15 | return cnt; 16 | } 17 | public static int count3(int[] a){ 18 | Arrays.sort(a); 19 | int N = a.length; 20 | int cnt = 0; 21 | for(int i = 0;ii) 24 | cnt++; 25 | } 26 | } 27 | return cnt; 28 | } 29 | public static void main(String[] args) { 30 | // TODO Auto-generated method stub 31 | // double prev = timeTrial(125); 32 | // for(int N = 250;true;N+=N){ 33 | // double time = timeTrial(N); 34 | // } 35 | 36 | int[] a = In.readInts(args[0]); 37 | StdOut.println(count(a)); 38 | StdOut.println(count3(a)); 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/graph/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.StdOut; 5 | 6 | public class DepthFirstSearch { 7 | 8 | private boolean[] marked; 9 | private int count; 10 | public DepthFirstSearch(Graph G,int s){ 11 | marked = new boolean[G.V()]; 12 | dfs(G,s); 13 | } 14 | 15 | private void dfs(Graph G,int v){ 16 | marked[v] = true; 17 | count ++; 18 | for(int w : G.adj(v)) 19 | if(!marked[w]) 20 | dfs(G,w); 21 | } 22 | 23 | public boolean marked(int w){ 24 | return marked[w]; 25 | } 26 | public int count(){ 27 | return count; 28 | } 29 | 30 | public static void main(String[] args) { 31 | Graph G = new Graph(new In(args[0])); 32 | int s = Integer.parseInt(args[1]); 33 | DepthFirstSearch search = new DepthFirstSearch(G,s); 34 | for(int v = 0; v < G.V(); v++){ 35 | if(search.marked(v)) 36 | StdOut.print(v + " "); 37 | } 38 | StdOut.println(); 39 | if(search.count() != G.V()) 40 | StdOut.print("Not "); 41 | StdOut.println("connected"); 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/graph/DepthFirstOrder.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.Queue; 4 | import edu.princeton.cs.algs4.Stack; 5 | 6 | public class DepthFirstOrder { 7 | 8 | private boolean[] marked; 9 | private Queue pre; 10 | private Queue post; 11 | private Stack reversePost; 12 | 13 | public DepthFirstOrder(Digraph G){ 14 | pre = new Queue(); 15 | post = new Queue(); 16 | reversePost = new Stack(); 17 | marked = new boolean[G.V()]; 18 | for(int v = 0; v < G.V();v++) 19 | if(!marked[v]) 20 | dfs(G,v); 21 | } 22 | 23 | private void dfs(Digraph G,int v){ 24 | pre.enqueue(v); 25 | marked[v] = true; 26 | for(int w :G.adj(v)) 27 | if(!marked[w]) 28 | dfs(G,w); 29 | post.enqueue(v); 30 | reversePost.push(v); 31 | } 32 | 33 | public Iterable pre(){ 34 | return pre; 35 | } 36 | public Iterable post(){ 37 | return post; 38 | } 39 | public Iterable reversePost(){ 40 | return reversePost; 41 | } 42 | public static void main(String[] args) { 43 | // TODO Auto-generated method stub 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/graph2/EdgeWeightedGraph.java: -------------------------------------------------------------------------------- 1 | package graph2; 2 | 3 | import edu.princeton.cs.algs4.Bag; 4 | import edu.princeton.cs.algs4.In; 5 | 6 | public class EdgeWeightedGraph { 7 | private final int V; 8 | private int E; 9 | private Bag[] adj; 10 | 11 | public EdgeWeightedGraph(int V){ 12 | this.V = V; 13 | this.E = 0; 14 | // adj = (Bag[])new Bag[v]; 15 | // for(int v= 0; v < V;v++){ 16 | // adj[v] = new Bag(); 17 | // } 18 | } 19 | // public EdgeWeightedGraph(In in){ 20 | // 21 | // } 22 | public int V(){ 23 | return V; 24 | } 25 | public int E(){ 26 | return E; 27 | } 28 | public void addEdge(Edge e){ 29 | int v = e.either(); 30 | int w = e.other(v); 31 | adj[v].add(e); 32 | adj[w].add(e); 33 | E++; 34 | } 35 | public Iterable adj(int v){ 36 | return adj[v]; 37 | } 38 | public Iterable edges(){ 39 | Bag b = new Bag(); 40 | for(int v = 0; v < V; v++){ 41 | for(Edge e: adj[v]) 42 | if(e.other(v)>v) 43 | b.add(e); 44 | } 45 | return b; 46 | } 47 | // public String toString(){ 48 | // 49 | // } 50 | public static void main(String[] args) { 51 | // TODO Auto-generated method stub 52 | 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/StopWatch.java: -------------------------------------------------------------------------------- 1 | import edu.princeton.cs.algs4.StdOut; 2 | import edu.princeton.cs.algs4.StdRandom; 3 | import edu.princeton.cs.algs4.ThreeSum; 4 | 5 | 6 | public class StopWatch { 7 | 8 | private final long start; 9 | public StopWatch(){ 10 | start = System.currentTimeMillis(); 11 | } 12 | public double elapsedTime(){ 13 | long now = System.currentTimeMillis(); 14 | return (now - start) /1000.0; 15 | } 16 | 17 | public static double timeTrial(int N){ 18 | int MAX = 1000000; 19 | int[] a = new int[N]; 20 | for(int i = 0;i < N;i ++){ 21 | a[i]= StdRandom.uniform(-MAX,MAX); 22 | } 23 | StopWatch timer = new StopWatch(); 24 | int cnt = ThreeSum.count(a); 25 | return timer.elapsedTime(); 26 | } 27 | public static void main(String[] args) { 28 | int N = Integer.parseInt(args[0]); 29 | int[] a = new int[N]; 30 | for(int i= 0;i < N;i++){ 31 | a[i] = StdRandom.uniform(-1000000,1000000); 32 | } 33 | StopWatch timer = new StopWatch(); 34 | int cnt = ThreeSum.count(a); 35 | double time = timer.elapsedTime(); 36 | StdOut.println(cnt + " triples " + time + " seconds"); 37 | 38 | 39 | for( N= 250 ;true;N+=N){ 40 | time = timeTrial(N); 41 | StdOut.printf("%7d %5.1f\n", N,time); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/graph/Digraph.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.Bag; 4 | import edu.princeton.cs.algs4.In; 5 | 6 | public class Digraph { 7 | 8 | private final int V; 9 | private int E; 10 | private Bag[] adj; 11 | public Digraph(int V){ 12 | this.V = V; 13 | this.E = 0; 14 | adj = (Bag[])new Bag[V]; 15 | for(int v = 0; v < V; v++){ 16 | adj[v] = new Bag(); 17 | } 18 | } 19 | public Digraph(In in){ 20 | this.V = in.readInt(); 21 | // this(in.readInt()); 22 | adj = (Bag[]) new Bag[V]; 23 | for (int v = 0; v < V; v++) { 24 | adj[v] = new Bag(); 25 | } 26 | int E = in.readInt(); 27 | for(int i= 0;i < E;i ++){ 28 | int v = in.readInt(); 29 | int w = in.readInt(); 30 | addEdge(v,w); 31 | } 32 | } 33 | public void addEdge(int v,int w){ 34 | adj[v].add(w); 35 | E++; 36 | } 37 | public int V(){ 38 | return V; 39 | } 40 | public int E(){ 41 | return E; 42 | } 43 | public Iterable adj(int v){ 44 | return adj[v]; 45 | } 46 | public Digraph reverse(){ 47 | Digraph R = new Digraph(V); 48 | for(int v = 0; v < V; v++){ 49 | for(int w : adj(v)) 50 | R.addEdge(w, v); 51 | } 52 | return R; 53 | } 54 | public static void main(String[] args) { 55 | 56 | 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/sort/SortCompare.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | import edu.princeton.cs.algs4.Heap; 4 | import edu.princeton.cs.algs4.Insertion; 5 | import edu.princeton.cs.algs4.Merge; 6 | import edu.princeton.cs.algs4.Quick; 7 | import edu.princeton.cs.algs4.Selection; 8 | import edu.princeton.cs.algs4.Shell; 9 | import edu.princeton.cs.algs4.StdRandom; 10 | import edu.princeton.cs.algs4.Stopwatch; 11 | 12 | public class SortCompare { 13 | 14 | public static double time(String alg,Double[] a){ 15 | Stopwatch timer = new Stopwatch(); 16 | if(alg.equals("Insertion")) 17 | Insertion.sort(a); 18 | if(alg.equals("Selection")) 19 | Selection.sort(a); 20 | if(alg.equals("Shell")) 21 | Shell.sort(a); 22 | if(alg.equals("Merge")) 23 | Merge.sort(a); 24 | if(alg.equals("Quick")) 25 | Quick.sort(a); 26 | if(alg.equals("Heap")) 27 | Heap.sort(a); 28 | return timer.elapsedTime(); 29 | } 30 | 31 | public static double timeRandomInput(String alg,int N,int T){ 32 | double total = 0.0; 33 | Double[] a = new Double[N]; 34 | for(int t = 0; t < T; t++){ 35 | for(int i = 0; i< N;i ++){ 36 | a [i] = StdRandom.uniform(); 37 | } 38 | total += time(alg,a); 39 | } 40 | return total; 41 | } 42 | public static void main(String[] args) { 43 | // TODO Auto-generated method stub 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/stack.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | public class stack implements Iterable{ 3 | private Node first; 4 | private int N; 5 | private class Node{ 6 | Item item; 7 | Node next; 8 | } 9 | public boolean isEmpty(){ 10 | return first == null; 11 | } 12 | public int size(){ 13 | return N; 14 | } 15 | public void push(Item item){ 16 | Node oldfirst = first; 17 | first = new Node(); 18 | first.item = item; 19 | first.next = oldfirst; 20 | N++; 21 | } 22 | public Item pop(){ 23 | Item item = first.item; 24 | first = first.next; 25 | N--; 26 | return item; 27 | } 28 | 29 | @Override 30 | public Iterator iterator() { 31 | // TODO Auto-generated method stub 32 | return new ListIterator(); 33 | } 34 | private class ListIterator implements Iterator{ 35 | private Node current = first; 36 | @Override 37 | public boolean hasNext() { 38 | // TODO Auto-generated method stub 39 | return current !=null; 40 | } 41 | 42 | @Override 43 | public Item next() { 44 | // TODO Auto-generated method stub] 45 | Item item = current.item; 46 | current = current.next; 47 | return item; 48 | } 49 | 50 | @Override 51 | public void remove() { 52 | // TODO Auto-generated method stub 53 | 54 | } 55 | 56 | } 57 | 58 | public static void main(String[] args){ 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/ResizingArrayStack.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | public class ResizingArrayStack implements Iterable{ 3 | 4 | private Item[] a = (Item[])new Object[1]; 5 | private int N = 0; 6 | public boolean isEmpty(){ 7 | return N == 0; 8 | } 9 | public int size(){ 10 | return N; 11 | } 12 | private void resize(int max){ 13 | Item[] temp = (Item[]) new Object[max]; 14 | for(int i = 0;i < N;i ++){ 15 | temp[i] = a[i]; 16 | } 17 | a = temp; 18 | } 19 | 20 | public void push(Item item){ 21 | if(N == a.length) 22 | resize(2*a.length); 23 | a[N++] = item; 24 | } 25 | 26 | public Item pop(){ 27 | Item item = a[--N]; 28 | a[N] = null; 29 | if(N>0 && N==a.length/4) 30 | resize(a.length/2); 31 | return item; 32 | } 33 | 34 | @Override 35 | public Iterator iterator() { 36 | // TODO Auto-generated method stub 37 | return new ReverseArrayIterator(); 38 | } 39 | private class ReverseArrayIterator implements Iterator{ 40 | private int i = N; 41 | @Override 42 | public boolean hasNext() { 43 | // TODO Auto-generated method stub 44 | return i>0; 45 | } 46 | 47 | @Override 48 | public Item next() { 49 | // TODO Auto-generated method stub 50 | return a[--i]; 51 | } 52 | 53 | @Override 54 | public void remove() { 55 | // TODO Auto-generated method stub 56 | 57 | } 58 | 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/graph/CC.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.Bag; 4 | import edu.princeton.cs.algs4.In; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class CC { 8 | 9 | private boolean[] marked; 10 | private int[] id; 11 | private int count; 12 | public CC(Graph G){ 13 | marked = new boolean[G.V()]; 14 | id = new int[G.V()]; 15 | for(int s = 0;s < G.V();s++){ 16 | if(!marked[s]){ 17 | dfs(G,s); 18 | count ++; 19 | } 20 | } 21 | } 22 | private void dfs(Graph G,int v){ 23 | marked[v] = true; 24 | id[v] = count; 25 | for(int w:G.adj(v)) 26 | if(!marked[w]) 27 | dfs(G,w); 28 | } 29 | 30 | public boolean connected(int v,int w){ 31 | return id[v] == id[w]; 32 | } 33 | public int id(int v){ 34 | return id[v]; 35 | } 36 | public int count(){ 37 | return count; 38 | } 39 | public static void main(String[] args) { 40 | Graph G = new Graph(new In(args[0])); 41 | CC cc = new CC(G); 42 | int M = cc.count(); 43 | StdOut.println(M + " components"); 44 | Bag[] components; 45 | components = (Bag[]) new Bag[M]; 46 | for(int i= 0;i < M;i ++){ 47 | components[i] = new Bag(); 48 | } 49 | for(int v = 0 ; v < G.V();v++){ 50 | components[cc.id[v]].add(v); 51 | } 52 | for(int i= 0; i < M;i++){ 53 | for(int v : components[i]){ 54 | StdOut.print(v + " "); 55 | } 56 | StdOut.println(); 57 | } 58 | 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/graph/DirectedCycle.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.Stack; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class DirectedCycle { 8 | 9 | private boolean[] marked; 10 | private int[] edgeTo; 11 | private Stack cycle; 12 | private boolean[] onStack; 13 | 14 | public DirectedCycle(Digraph G){ 15 | onStack = new boolean[G.V()]; 16 | edgeTo = new int[G.V()]; 17 | marked = new boolean[G.V()]; 18 | for(int v = 0;v < G.V(); v++) 19 | if(!marked[v]) 20 | dfs(G,v); 21 | } 22 | private void dfs(Digraph G,int v){ 23 | onStack[v] = true; 24 | marked[v] = true; 25 | for(int w:G.adj(v)){ 26 | if(this.hasCycle()) 27 | return; 28 | else if(!marked[w]){ 29 | edgeTo[w] = v; 30 | dfs(G,w); 31 | }else if(onStack[w]){ 32 | cycle = new Stack(); 33 | for(int x= v; x != w;x = edgeTo[x]){ 34 | cycle.push(x); 35 | } 36 | cycle.push(w); 37 | cycle.push(v); 38 | 39 | } 40 | } 41 | onStack[v] = false; 42 | } 43 | public boolean hasCycle(){ 44 | return cycle !=null; 45 | } 46 | public Iterable cycle(){ 47 | return cycle; 48 | } 49 | public static void main(String[] args) { 50 | In in = new In(args[0]); 51 | Digraph G = new Digraph( in); 52 | DirectedCycle dc = new DirectedCycle(G); 53 | if(dc.hasCycle()){ 54 | for(int v : dc.cycle){ 55 | StdOut.print(v + " "); 56 | } 57 | } 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/graph/DepthFirstPaths.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.Stack; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class DepthFirstPaths { 8 | 9 | private boolean[] marked; 10 | private int[] edgeTo; 11 | private final int s; 12 | 13 | public DepthFirstPaths(Graph G,int s){ 14 | marked = new boolean[G.V()]; 15 | edgeTo = new int[G.V()]; 16 | this.s = s; 17 | dfs(G,s); 18 | } 19 | 20 | private void dfs(Graph G,int v){ 21 | marked[v] = true; 22 | for(int w : G.adj(v)){ 23 | if(!marked[w]){ 24 | edgeTo[w] = v; 25 | dfs(G,w); 26 | } 27 | } 28 | } 29 | 30 | public boolean hasPathTo(int v){ 31 | return marked[v]; 32 | } 33 | 34 | public Iterable pathTo(int v){ 35 | if(!hasPathTo(v)) 36 | return null; 37 | Stack path = new Stack(); 38 | for(int x = v; x != s; x = edgeTo[x]){ 39 | path.push(x); 40 | } 41 | path.push(s); 42 | return path; 43 | } 44 | 45 | public static void main(String[] args) { 46 | Graph G = new Graph(new In(args[0])); 47 | int s = Integer.parseInt(args[1]); 48 | DepthFirstPaths search = new DepthFirstPaths(G,s); 49 | for(int v = 0; v < G.V(); v++){ 50 | StdOut.print(s + " to " + v + ": "); 51 | if(search.hasPathTo(v)){ 52 | for(int x : search.pathTo(v)) 53 | if(x==s) 54 | StdOut.print(x); 55 | else 56 | StdOut.print("-" + x); 57 | }else{ 58 | StdOut.print("null"); 59 | } 60 | StdOut.println(); 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/graph/DirectedDFS.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.Bag; 4 | import edu.princeton.cs.algs4.In; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class DirectedDFS { 8 | 9 | private boolean[] marked; 10 | public DirectedDFS(Digraph G,int s){ 11 | marked = new boolean[G.V()]; 12 | dfs(G,s); 13 | } 14 | public DirectedDFS(Digraph G,Iterable sources){ 15 | marked = new boolean[G.V()]; 16 | for(int s : sources){ 17 | if(!marked[s]) 18 | dfs(G,s); 19 | } 20 | } 21 | public boolean marked(int v){ 22 | return marked[v]; 23 | } 24 | private void dfs(Digraph G,int v){ 25 | marked[v] = true; 26 | for(int w: G.adj(v)) 27 | if(!marked[w]) 28 | dfs(G,w); 29 | } 30 | 31 | 32 | public static void main(String[] args) { 33 | // read in digraph from command-line argument 34 | In in = new In(args[0]); 35 | Digraph G = new Digraph( in); 36 | 37 | 38 | // read in sources from command-line arguments 39 | Bag sources = new Bag(); 40 | for (int i = 1; i < args.length; i++) { 41 | int s = Integer.parseInt(args[i]); 42 | sources.add(s); 43 | } 44 | 45 | // multiple-source reachability 46 | DirectedDFS dfs = new DirectedDFS(G, sources); 47 | 48 | // print out vertices reachable from sources 49 | for (int v = 0; v < G.V(); v++) { 50 | if (dfs.marked(v)) StdOut.print(v + " "); 51 | } 52 | StdOut.println(); 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/graph/BreadthFirstPaths.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.Queue; 5 | import edu.princeton.cs.algs4.Stack; 6 | import edu.princeton.cs.algs4.StdOut; 7 | 8 | public class BreadthFirstPaths { 9 | 10 | private boolean[] marked; 11 | private int[] edgeTo; 12 | private final int s; 13 | 14 | public BreadthFirstPaths(Graph G,int s){ 15 | marked = new boolean[G.V()]; 16 | edgeTo = new int[G.V()]; 17 | this.s = s; 18 | bfs(G,s); 19 | } 20 | private void bfs(Graph G,int s){ 21 | Queue queue = new Queue(); 22 | marked[s] = true; 23 | queue.enqueue(s); 24 | while(!queue.isEmpty()){ 25 | int v = queue.dequeue(); 26 | for(int w : G.adj(v)){ 27 | if(!marked[w]) 28 | { 29 | edgeTo[w] = v; 30 | marked[w] = true; 31 | queue.enqueue(w); 32 | } 33 | } 34 | 35 | } 36 | } 37 | 38 | public boolean hasPathTo(int v){ 39 | return marked[v]; 40 | } 41 | public Iterable pathTo(int v){ 42 | if(!hasPathTo(v)) 43 | return null; 44 | Stack path = new Stack(); 45 | for(int x = v; x != s; x = edgeTo[x]){ 46 | path.push(x); 47 | } 48 | path.push(s); 49 | return path; 50 | } 51 | public static void main(String[] args) { 52 | Graph G = new Graph(new In(args[0])); 53 | int s = Integer.parseInt(args[1]); 54 | BreadthFirstPaths search = new BreadthFirstPaths(G,s); 55 | for(int v = 0; v < G.V(); v++){ 56 | StdOut.print(s + " to " + v + ": "); 57 | if(search.hasPathTo(v)){ 58 | for(int x : search.pathTo(v)) 59 | if(x==s) 60 | StdOut.print(x); 61 | else 62 | StdOut.print("-" + x); 63 | }else{ 64 | StdOut.print("null"); 65 | } 66 | StdOut.println(); 67 | } 68 | 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/graph/KosarajuSCC.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.Queue; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class KosarajuSCC { 8 | 9 | private boolean[] marked; 10 | private int[] id; 11 | private int count; 12 | 13 | public KosarajuSCC(Digraph G){ 14 | marked = new boolean[G.V()]; 15 | id = new int[G.V()]; 16 | DepthFirstOrder order = new DepthFirstOrder(G.reverse()); 17 | for(int s : order.reversePost()){ 18 | if(!marked[s]){ 19 | dfs(G,s); 20 | count ++; 21 | } 22 | } 23 | } 24 | private void dfs(Digraph G,int v){ 25 | marked[v] = true; 26 | id[v] = count; 27 | for(int w : G.adj(v)){ 28 | if(!marked[w]) 29 | dfs(G,w); 30 | } 31 | } 32 | 33 | public boolean stronglyConnect(int v ,int w){ 34 | return id[v]==id[w]; 35 | } 36 | public int id(int v){ 37 | return id[v]; 38 | } 39 | 40 | public int count(){ 41 | return count; 42 | } 43 | public static void main(String[] args) { 44 | In in = new In(args[0]); 45 | Digraph G = new Digraph( in); 46 | KosarajuSCC ks = new KosarajuSCC(G); 47 | int M = ks.count; 48 | StdOut.println(M + " components"); 49 | // compute list of vertices in each strong component 50 | Queue[] components = (Queue[]) new Queue[M]; 51 | for (int i = 0; i < M; i++) { 52 | components[i] = new Queue(); 53 | } 54 | for (int v = 0; v < G.V(); v++) { 55 | components[ks.id(v)].enqueue(v); 56 | } 57 | 58 | // print results 59 | for (int i = 0; i < M; i++) { 60 | for (int v : components[i]) { 61 | StdOut.print(v + " "); 62 | } 63 | StdOut.println(); 64 | } 65 | 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/graph/Graph.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.Bag; 4 | import edu.princeton.cs.algs4.In; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class Graph { 8 | private final int V; 9 | private int E; 10 | private Bag[] adj; 11 | 12 | public Graph(int V){ 13 | StdOut.println(V); 14 | this.V = V; 15 | this.E = 0; 16 | adj = (Bag[]) new Bag[V]; 17 | for(int v = 0;v < V;v++){ 18 | adj[v] = new Bag(); 19 | } 20 | } 21 | public Graph(In in){ 22 | 23 | this(in.readInt()); 24 | int E = in.readInt(); 25 | for(int i= 0;i < E;i ++){ 26 | int v = in.readInt(); 27 | int w = in.readInt(); 28 | addEdge(v,w); 29 | } 30 | } 31 | int V(){ 32 | return V; 33 | } 34 | int E(){ 35 | return E; 36 | } 37 | public void addEdge(int v,int w){ 38 | adj[v].add(w); 39 | adj[w].add(v); 40 | E++; 41 | } 42 | Iterable adj(int v){ 43 | return adj[v]; 44 | } 45 | public String toString(){ 46 | String s = V + " vertices" + E+" edges\n"; 47 | for(int v = 0;v < V;v++){ 48 | s += v + ": "; 49 | for(int w:this.adj(v)) 50 | s+= w + " "; 51 | } 52 | return s; 53 | } 54 | 55 | public static int degree(Graph G,int v){ 56 | int degree = 0; 57 | for(int w : G.adj(v)) 58 | degree++; 59 | return degree; 60 | } 61 | public static int maxDegree(Graph G){ 62 | int max = 0; 63 | for(int v = 0; v < G.V();v++){ 64 | if(degree(G,v) > max) 65 | max = degree(G,v); 66 | } 67 | return max; 68 | } 69 | 70 | public static double avgDegree(Graph G){ 71 | return 2.0*G.E()/G.V(); 72 | } 73 | public static int numberOfSelfLoops(Graph G){ 74 | int count = 0; 75 | for(int v = 0; v < G.V(); v++){ 76 | for(int w : G.adj(v)) 77 | if(v==w) 78 | count ++; 79 | } 80 | return count/2; 81 | } 82 | 83 | public static void main(String[] args) { 84 | // TODO Auto-generated method stub 85 | 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/st/SequentialSearchST.java: -------------------------------------------------------------------------------- 1 | package st; 2 | 3 | import edu.princeton.cs.algs4.Queue; 4 | import edu.princeton.cs.algs4.StdIn; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class SequentialSearchST { 8 | private Node first; 9 | private int N = 0;; 10 | private class Node{ 11 | Key key; 12 | Value val; 13 | Node next; 14 | public Node(Key key,Value val,Node next){ 15 | this.key = key; 16 | this.val = val; 17 | this.next = next; 18 | } 19 | } 20 | 21 | public void put(Key key,Value val){ 22 | for(Node x = first;x != null;x = x.next){ 23 | if(key.equals(x.key)){ 24 | x.val = val; 25 | return; 26 | } 27 | } 28 | first = new Node(key,val,first); 29 | N++; 30 | } 31 | public Value get(Key key){ 32 | for(Node x = first;x != null; x = x.next){ 33 | if(key.equals(x.key)){ 34 | return x.val; 35 | } 36 | } 37 | return null; 38 | } 39 | public int size(){ 40 | return N; 41 | } 42 | 43 | public Iterable keys(){ 44 | Queue queue = new Queue(); 45 | for(Node x = first;x !=null;x = x.next){ 46 | queue.enqueue(x.key); 47 | } 48 | return queue; 49 | } 50 | 51 | public void delete_delay(Key key){ 52 | put(key,null); 53 | } 54 | public void delete(Key key){ 55 | first = delete(first,key); 56 | } 57 | private Node delete(Node x,Key key){ 58 | if(x == null) 59 | return null; 60 | if(key.equals(x.key)){ 61 | N--; 62 | return x.next; 63 | } 64 | x.next = delete(x.next,key); 65 | return x; 66 | } 67 | public boolean contains(Key key){ 68 | return get(key)!=null; 69 | } 70 | public boolean isEmpty(){ 71 | return size()==0; 72 | } 73 | 74 | 75 | public static void main(String[] args){ 76 | SequentialSearchST st; 77 | st = new SequentialSearchST(); 78 | 79 | for(int i = 0; !StdIn.isEmpty();i++){ 80 | String key = StdIn.readString(); 81 | st.put(key, i); 82 | } 83 | 84 | for(String s : st.keys()){ 85 | StdOut.println(s + " " + st.get(s)); 86 | } 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/sort/MaxPQ.java: -------------------------------------------------------------------------------- 1 | package sort; 2 | 3 | public class MaxPQ> { 4 | private Key[] pq; 5 | private int N = 0; 6 | public MaxPQ(int maxN){ 7 | pq = (Key[]) new Comparable[maxN+1]; 8 | } 9 | public boolean isEmpty(){ 10 | return N == 0; 11 | } 12 | public int size(){ 13 | return N; 14 | } 15 | public void insert(Key v){ 16 | pq[++N] = v; 17 | swim(N); 18 | } 19 | public Key delMax(){ 20 | Key max = pq[1]; 21 | exch(1,N--); 22 | pq[N+1] = null; 23 | sink(1); 24 | return max; 25 | } 26 | 27 | private boolean less(int i,int j){ 28 | return pq[i].compareTo(pq[j]) < 0; 29 | } 30 | private void exch(int i,int j){ 31 | Key t = pq[i]; 32 | pq[i] = pq[j]; 33 | pq[j] = t; 34 | } 35 | 36 | private void swim(int k){ 37 | while(k > 1 && less(k/2,k)) 38 | { 39 | exch(k/2,k); 40 | k = k/2; 41 | } 42 | } 43 | 44 | private void sink(int k){ 45 | while(2*k <= N){ 46 | int j = 2*k; 47 | if(j < N & less(j,j+1)) 48 | j++; 49 | if(!less(k,j)) 50 | break; 51 | exch(k,j); 52 | k = j; 53 | } 54 | } 55 | 56 | 57 | public static void sort(Comparable[] a){ 58 | int N = a.length; 59 | for(int k = N/2;k >=1;k--){ 60 | sink(a,k,N); 61 | } 62 | while(N>1){ 63 | exch(a,1,N--); 64 | sink(a,1,N); 65 | } 66 | } 67 | 68 | public static void sink(Comparable[] a,int k,int N){ 69 | while(2*k <=N){ 70 | int j = 2*k; 71 | if(j < N && less2(j,j++)) 72 | j++; 73 | if(!less2(k,j)){ 74 | break; 75 | } 76 | exch(a,k,j); 77 | k = j; 78 | } 79 | } 80 | public static void exch(Comparable[] a,int i,int j){ 81 | Comparable t = a[i]; 82 | a[i] = a[j]; 83 | a[j] = t; 84 | } 85 | private static boolean less2(Comparable v,Comparable w){ 86 | return v.compareTo(w) < 0; 87 | } 88 | 89 | public void test(int t,int x){ 90 | 91 | } 92 | 93 | public void test(int x,double y){ 94 | 95 | } 96 | 97 | public static void main(String[] args) { 98 | 99 | } 100 | 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/graph/SymbolGraph.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | import edu.princeton.cs.algs4.ST; 5 | import edu.princeton.cs.algs4.StdIn; 6 | import edu.princeton.cs.algs4.StdOut; 7 | 8 | public class SymbolGraph { 9 | 10 | private ST st; 11 | private String[] keys; 12 | private Graph G; 13 | 14 | public SymbolGraph(String stream,String sp){ 15 | st = new ST(); 16 | In in = new In(stream); 17 | while(in.hasNextLine()){ 18 | String[] a = in.readLine().split(sp); 19 | for(int i = 0;i < a.length; i++){ 20 | if(!st.contains(a[i])) 21 | st.put(a[i], st.size()); 22 | } 23 | } 24 | keys = new String[st.size()]; 25 | for(String name : st.keys()) 26 | keys[st.get(name)] = name; 27 | G = new Graph(st.size()); 28 | in = new In(stream); 29 | while(in.hasNextLine()){ 30 | String[] a = in.readLine().split(sp); 31 | int v = st.get(a[0]); 32 | for(int i = 1;i < a.length;i++){ 33 | G.addEdge(v, st.get(a[i])); 34 | } 35 | } 36 | } 37 | public boolean contains(String s){ 38 | return st.contains(s); 39 | } 40 | public int index(String s){ 41 | return st.get(s); 42 | } 43 | public String name(int v){ 44 | return keys[v]; 45 | } 46 | public Graph G(){ 47 | return G; 48 | } 49 | public static void main(String[] args) { 50 | // String filename = args[0]; 51 | // String delim = args[1]; 52 | // SymbolGraph sg = new SymbolGraph(filename,delim); 53 | // Graph G = sg.G(); 54 | // while(StdIn.hasNextLine()){ 55 | // String source = StdIn.readLine(); 56 | // for(int w : G.adj(sg.index(source))) 57 | // StdOut.println(" "+sg.name(w)); 58 | // } 59 | 60 | 61 | /**/ 62 | SymbolGraph sg = new SymbolGraph(args[0],args[1]); 63 | Graph G = sg.G(); 64 | String source = args[2]; 65 | if(!sg.contains(source)){ 66 | StdOut.println(source + " not int database"); 67 | return; 68 | } 69 | int s = sg.index(source); 70 | BreadthFirstPaths bfs = new BreadthFirstPaths(G,s); 71 | while(!StdIn.isEmpty()){ 72 | String sink = StdIn.readLine(); 73 | if(sg.contains(sink)){ 74 | int t = sg.index(sink); 75 | if(bfs.hasPathTo(t)) 76 | for(int v : bfs.pathTo(t)){ 77 | StdOut.println(" "+sg.name(v)); 78 | }else{ 79 | StdOut.println("Not connected."); 80 | } 81 | }else{ 82 | StdOut.println("Not in database."); 83 | } 84 | 85 | } 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/st/BinarySearchST.java: -------------------------------------------------------------------------------- 1 | package st; 2 | 3 | import edu.princeton.cs.algs4.Queue; 4 | import edu.princeton.cs.algs4.StdIn; 5 | import edu.princeton.cs.algs4.StdOut; 6 | 7 | public class BinarySearchST,Value> { 8 | 9 | private Key[] keys; 10 | private Value[] vals; 11 | private int N; 12 | public BinarySearchST(int capacity){ 13 | keys = (Key[])new Comparable[capacity]; 14 | vals = (Value[]) new Object[capacity]; 15 | } 16 | 17 | public void put(Key key,Value val){ 18 | int i = rank(key); 19 | if(i < N && keys[i].compareTo(key)==0){ 20 | vals[i] = val; 21 | return; 22 | } 23 | for(int j = N;j > i;j--){ 24 | keys[j] = keys[j-1]; 25 | vals[j] = vals[j-1]; 26 | } 27 | keys[i] = key; 28 | vals[i] = val; 29 | N++; 30 | } 31 | public int rank(Key key,int lo,int hi){ 32 | if(hi < lo) 33 | return lo; 34 | int mid = lo + (hi -lo)/2; 35 | int cmp = key.compareTo(keys[mid]); 36 | if(cmp < 0) 37 | return rank(key,lo,mid -1); 38 | else if(cmp >0){ 39 | return rank(key,mid+1,hi); 40 | }else{ 41 | return mid; 42 | } 43 | } 44 | public int rank(Key key){ 45 | int lo = 0,hi = N-1; 46 | while(lo <= hi){ 47 | int mid = lo + (hi -lo)/2; 48 | int cmp = key.compareTo(keys[mid]); 49 | if(cmp < 0) 50 | hi = mid -1; 51 | else if(cmp >0) 52 | lo = mid +1; 53 | else return mid; 54 | } 55 | return lo; 56 | } 57 | 58 | public Key min(){ 59 | return keys[0]; 60 | } 61 | public Key max(){ 62 | return keys[N-1]; 63 | } 64 | public Key select(int k){ 65 | return keys[k]; 66 | } 67 | 68 | public Key ceiling(Key key){ 69 | int i = rank(key); 70 | if(i == N) 71 | return null; 72 | return keys[i]; 73 | } 74 | public Key floor(Key key){ 75 | int i = rank(key); 76 | if(i < N && key.compareTo(keys[i])==0){ 77 | return keys[i]; 78 | } 79 | else if(i ==0) 80 | return null; 81 | else{ 82 | return keys[i-1]; 83 | } 84 | 85 | } 86 | public Value get(Key key){ 87 | if(isEmpty()) 88 | return null; 89 | int i = rank(key); 90 | if(i < N && keys[i].compareTo(key)==0) 91 | return vals[i]; 92 | else 93 | return null; 94 | 95 | } 96 | public void delete(Key key,Value val){ 97 | int i = rank(key); 98 | if(i == N || key.compareTo(keys[i])!=0){ 99 | return; 100 | } 101 | // if(i < N && key.compareTo(keys[i])==0){ 102 | for(int j = i;j < N; j++){ 103 | keys[j] = keys[j++]; 104 | vals[j] = vals[j++]; 105 | } 106 | // } 107 | N--; 108 | keys[N] = null; 109 | vals[N] = null; 110 | 111 | } 112 | public boolean contains(Key key){ 113 | return get(key)!=null; 114 | } 115 | public boolean isEmpty(){ 116 | return size()==0; 117 | } 118 | public int size(){ 119 | return N; 120 | } 121 | public Iterable keys(Key lo,Key hi){ 122 | Queue q = new Queue(); 123 | for(int i=rank(lo);i < rank(hi);i++){ 124 | q.enqueue(keys[i]); 125 | } 126 | if(contains(hi)){ 127 | q.enqueue(keys[rank(hi)]); 128 | } 129 | return q; 130 | } 131 | 132 | public static void main(String[] args){ 133 | BinarySearchST st; 134 | st = new BinarySearchST(20); 135 | 136 | for(int i = 0; !StdIn.isEmpty();i++){ 137 | String key = StdIn.readString(); 138 | st.put(key, i); 139 | } 140 | 141 | for(String s : st.keys("A", "Z")){ 142 | StdOut.println(s + " " + st.get(s)); 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/st/BST.java: -------------------------------------------------------------------------------- 1 | package st; 2 | 3 | import edu.princeton.cs.algs4.Queue; 4 | import edu.princeton.cs.algs4.StdOut; 5 | 6 | public class BST,Value> { 7 | private Node root; 8 | private class Node{ 9 | private Key key; 10 | private Value val; 11 | private Node left,right; 12 | private int N; 13 | 14 | public Node(Key key,Value val,int N){ 15 | this.key = key; 16 | this.val = val; 17 | this.N = N; 18 | } 19 | } 20 | 21 | public int size(){ 22 | return size(root); 23 | } 24 | private int size(Node x){ 25 | if(x == null) return 0; 26 | else 27 | return x.N; 28 | } 29 | 30 | public Value get(Key key){ 31 | return get(root,key); 32 | } 33 | private Value get(Node x,Key key){ 34 | if(x == null) 35 | return null; 36 | int cmp = key.compareTo(x.key); 37 | if(cmp <0) 38 | return get(x.left,key); 39 | else if(cmp > 0) 40 | return get(x.right,key); 41 | else 42 | return x.val; 43 | } 44 | public void put(Key key,Value val){ 45 | root = put(root,key,val); 46 | } 47 | 48 | private Node put(Node x,Key key,Value val){ 49 | if(x == null) 50 | return new Node(key,val,1); 51 | int cmp = key.compareTo(x.key); 52 | if(cmp <0){ 53 | x.left = put(x.left,key,val); 54 | }else if(cmp > 0) 55 | x.right = put(x.right,key,val); 56 | else x.val = val; 57 | x.N = size(x.left) + size(x.right) +1; 58 | return x; 59 | } 60 | 61 | public Key min(){ 62 | return min(root).key; 63 | } 64 | private Node min(Node x){ 65 | if(x.left==null) 66 | return x; 67 | return min(x.left); 68 | } 69 | public Key max(){ 70 | return max(root).key; 71 | } 72 | private Node max(Node x){ 73 | if(x.right==null) 74 | return x; 75 | return max(x.right); 76 | } 77 | public Key floor(Key key){ 78 | Node x = floor(root,key); 79 | if(x == null) 80 | return null; 81 | return x.key; 82 | } 83 | 84 | private Node floor(Node x,Key key){ 85 | if(x == null) 86 | return null; 87 | int cmp = key.compareTo(x.key); 88 | if(cmp == 0) 89 | return x; 90 | if(cmp <0) 91 | return floor(x.left,key); 92 | Node t = floor(x.right,key); 93 | if(t != null) 94 | return t; 95 | else 96 | return x; 97 | 98 | } 99 | 100 | public Key select(int k){ 101 | return select(root,k).key; 102 | } 103 | private Node select(Node x,int k){ 104 | if(x == null) 105 | return null; 106 | int t = size(x.left); 107 | if(t > k) 108 | return select(x.left,k); 109 | else if( t < k) 110 | return select(x.right,t-k-1); 111 | else return x; 112 | } 113 | 114 | public int rank(Key key){ 115 | return rank(key,root); 116 | } 117 | private int rank(Key key,Node x){ 118 | if(x==null) 119 | return 0; 120 | int cmp = key.compareTo(x.key); 121 | if(cmp < 0) 122 | return rank(key,x.left); 123 | else if(cmp>0) 124 | return 1 - size(x.left) + rank(key,x.right); 125 | else 126 | return size(x.left); 127 | } 128 | 129 | public void deleteMin(){ 130 | root = deleteMin(root); 131 | } 132 | 133 | private Node deleteMin(Node x){ 134 | if(x.left==null) 135 | return x.right; 136 | x.left = deleteMin(x.left); 137 | x.N=size(x.left)+size(x.right)+1; 138 | return x; 139 | } 140 | public void delete(Key key){ 141 | root = delete(root,key); 142 | } 143 | 144 | private Node delete(Node x,Key key){ 145 | if(x==null) 146 | return null; 147 | int cmp = key.compareTo(x.key); 148 | if(cmp < 0) 149 | x.left = delete(x.left,key); 150 | else if(cmp >0) 151 | x.right = delete(x.right,key); 152 | else{ 153 | if(x.right==null) 154 | return x.left; 155 | if(x.left==null) 156 | return x.right; 157 | Node t = x; 158 | x = min(t.right); 159 | x.right = deleteMin(t.right); 160 | x.left = t.left; 161 | } 162 | x.N = size(x.left) +size(x.right)+1; 163 | return x; 164 | } 165 | 166 | public Iterable keys(){ 167 | return keys(min(),max()); 168 | } 169 | 170 | public Iterable keys(Key lo,Key hi){ 171 | Queue queue = new Queue(); 172 | keys(root,queue,lo,hi); 173 | return queue; 174 | 175 | } 176 | private void keys(Node x,Queue queue,Key lo,Key hi){ 177 | if(x==null) 178 | return; 179 | int cmplo = lo.compareTo(x.key); 180 | int cmphi = lo.compareTo(x.key); 181 | if(cmplo < 0) 182 | keys(x.left,queue,lo,hi); 183 | if(cmplo <=0 && cmphi>=0) 184 | queue.enqueue(x.key); 185 | if(cmphi>0) 186 | keys(x.right,queue,lo,hi); 187 | 188 | 189 | } 190 | private void print(Node x){ 191 | if(x==null) 192 | return; 193 | print(x.left); 194 | StdOut.println(x.key); 195 | print(x.right); 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/WeightedQuickUnionPathHalvingUF.java: -------------------------------------------------------------------------------- 1 | import edu.princeton.cs.algs4.StdIn; 2 | import edu.princeton.cs.algs4.StdOut; 3 | 4 | 5 | /****************************************************************************** 6 | * Compilation: javac WeightedQuickUnionPathHalvingUF.java 7 | * Execution: java WeightedQuickUnionPathHalvingUF < input.txt 8 | * Dependencies: StdIn.java StdOut.java 9 | * 10 | * Weighted quick-union with path splitting. 11 | * 12 | ******************************************************************************/ 13 | 14 | 15 | /** 16 | * The WeightedQuickUnionPathHalvingUF class represents a 17 | * union-find data structure. 18 | * It supports the union and find operations, along with 19 | * methods for determining whether two sites are in the same component 20 | * and the total number of components. 21 | *

22 | * This implementation uses weighted quick union (by size) 23 | * with path compaction (via halving). 24 | * Initializing a data structure with N sites takes linear time. 25 | * Afterwards, union, find, and connected take 26 | * logarithmic time (in the worst case) and count takes constant 27 | * time. Moreover, the amortized time per union, find, 28 | * and connected operation has inverse Ackermann complexity. 29 | *

30 | * For additional documentation, see Section 1.5 of 31 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 32 | * 33 | * @author Robert Sedgewick 34 | * @author Kevin Wayne 35 | */ 36 | public class WeightedQuickUnionPathHalvingUF { 37 | private int[] parent; // parent[i] = parent of i 38 | private int[] size; // size[i] = number of sites in tree rooted at i 39 | // Note: not necessarily correct if i is not a root node 40 | private int count; // number of components 41 | 42 | /** 43 | * Initializes an empty union-find data structure with N sites 44 | * 0 through N-1. Each site is initially in its own 45 | * component. 46 | * 47 | * @param N the number of sites 48 | * @throws IllegalArgumentException if N < 0 49 | */ 50 | public WeightedQuickUnionPathHalvingUF(int N) { 51 | count = N; 52 | parent = new int[N]; 53 | size = new int[N]; 54 | for (int i = 0; i < N; i++) { 55 | parent[i] = i; 56 | size[i] = 1; 57 | } 58 | } 59 | 60 | /** 61 | * Returns the number of components. 62 | * 63 | * @return the number of components (between 1 and N) 64 | */ 65 | public int count() { 66 | return count; 67 | } 68 | 69 | /** 70 | * Returns the component identifier for the component containing site p. 71 | * 72 | * @param p the integer representing one object 73 | * @return the component identifier for the component containing site p 74 | * @throws IndexOutOfBoundsException unless 0 ≤ p < N 75 | */ 76 | public int find(int p) { 77 | validate(p); 78 | while (p != parent[p]) { 79 | parent[p] = parent[parent[p]]; // path compression by halving 80 | p = parent[p]; 81 | } 82 | return p; 83 | } 84 | 85 | // validate that p is a valid index 86 | private void validate(int p) { 87 | int N = parent.length; 88 | if (p < 0 || p >= N) { 89 | throw new IndexOutOfBoundsException("index " + p + " is not between 0 and " + (N-1)); 90 | } 91 | } 92 | 93 | /** 94 | * Returns true if the the two sites are in the same component. 95 | * 96 | * @param p the integer representing one site 97 | * @param q the integer representing the other site 98 | * @return true if the two sites p and q are in the same component; 99 | * false otherwise 100 | * @throws IndexOutOfBoundsException unless 101 | * both 0 ≤ p < N and 0 ≤ q < N 102 | */ 103 | public boolean connected(int p, int q) { 104 | return find(p) == find(q); 105 | } 106 | 107 | /** 108 | * Merges the component containing site p with the 109 | * the component containing site q. 110 | * 111 | * @param p the integer representing one site 112 | * @param q the integer representing the other site 113 | * @throws IndexOutOfBoundsException unless 114 | * both 0 ≤ p < N and 0 ≤ q < N 115 | */ 116 | public void union(int p, int q) { 117 | int rootP = find(p); 118 | int rootQ = find(q); 119 | if (rootP == rootQ) return; 120 | 121 | // make smaller root point to larger one 122 | if (size[rootP] < size[rootQ]) { 123 | parent[rootP] = rootQ; 124 | size[rootQ] += size[rootP]; 125 | } 126 | else { 127 | parent[rootQ] = rootP; 128 | size[rootP] += size[rootQ]; 129 | } 130 | count--; 131 | } 132 | 133 | 134 | /** 135 | * Reads in a sequence of pairs of integers (between 0 and N-1) from standard input, 136 | * where each integer represents some object; 137 | * if the sites are in different components, merge the two components 138 | * and print the pair to standard output. 139 | */ 140 | public static void main(String[] args) { 141 | int N = StdIn.readInt(); 142 | WeightedQuickUnionPathHalvingUF uf = new WeightedQuickUnionPathHalvingUF(N); 143 | while (!StdIn.isEmpty()) { 144 | int p = StdIn.readInt(); 145 | int q = StdIn.readInt(); 146 | if (uf.connected(p, q)) continue; 147 | uf.union(p, q); 148 | StdOut.println(p + " " + q); 149 | } 150 | StdOut.println(uf.count() + " components"); 151 | } 152 | 153 | } 154 | --------------------------------------------------------------------------------