17 | * The add, isEmpty, and size operation 18 | * take constant time. Iteration takes time proportional to the number of items. 19 | *
20 | * For additional documentation, see Section 1.3 of
21 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
22 | */
23 | public class Bag
11 | * For additional documentation, see
12 | * Section 3.2 of
13 | * Introduction to Programming in Java: An Interdisciplinary Approach
14 | * by Robert Sedgewick and Kevin Wayne.
15 | */
16 |
17 |
18 |
19 | public class Stopwatch {
20 |
21 | private final long start;
22 |
23 | /**
24 | * Create a stopwatch object.
25 | */
26 | public Stopwatch() {
27 | start = System.currentTimeMillis();
28 | }
29 |
30 |
31 | /**
32 | * Return elapsed time (in seconds) since this object was created.
33 | */
34 | public double elapsedTime() {
35 | long now = System.currentTimeMillis();
36 | return (now - start) / 1000.0;
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/1-Fundamentals/1-4-AnalysisOfAlgorithms/ThreeSum.java:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 | * Compilation: javac ThreeSum.java
3 | * Execution: java ThreeSum input.txt
4 | * Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt
5 | * http://algs4.cs.princeton.edu/14analysis/2Kints.txt
6 | * http://algs4.cs.princeton.edu/14analysis/4Kints.txt
7 | * http://algs4.cs.princeton.edu/14analysis/8Kints.txt
8 | * http://algs4.cs.princeton.edu/14analysis/16Kints.txt
9 | * http://algs4.cs.princeton.edu/14analysis/32Kints.txt
10 | * http://algs4.cs.princeton.edu/14analysis/1Mints.txt
11 | *
12 | * A program with cubic running time. Read in N integers
13 | * and counts the number of triples that sum to exactly 0
14 | * (ignoring integer overflow).
15 | *
16 | * % java ThreeSum 1Kints.txt
17 | * 70
18 | *
19 | * % java ThreeSum 2Kints.txt
20 | * 528
21 | *
22 | * % java ThreeSum 4Kints.txt
23 | * 4039
24 | *
25 | *************************************************************************/
26 |
27 | public class ThreeSum {
28 |
29 | // print distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0
30 | public static void printAll(int[] a) {
31 | int N = a.length;
32 | for (int i = 0; i < N; i++) {
33 | for (int j = i+1; j < N; j++) {
34 | for (int k = j+1; k < N; k++) {
35 | if (a[i] + a[j] + a[k] == 0) {
36 | StdOut.println(a[i] + " " + a[j] + " " + a[k]);
37 | }
38 | }
39 | }
40 | }
41 | }
42 |
43 | // return number of distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0
44 | public static int count(int[] a) {
45 | int N = a.length;
46 | int cnt = 0;
47 | for (int i = 0; i < N; i++) {
48 | for (int j = i+1; j < N; j++) {
49 | for (int k = j+1; k < N; k++) {
50 | if (a[i] + a[j] + a[k] == 0) {
51 | cnt++;
52 | }
53 | }
54 | }
55 | }
56 | return cnt;
57 | }
58 |
59 | public static void main(String[] args) {
60 | int[] a = In.readInts(args[0]);
61 |
62 | Stopwatch timer = new Stopwatch();
63 | int cnt = count(a);
64 | StdOut.println("elapsed time = " + timer.elapsedTime());
65 | StdOut.println(cnt);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/1-Fundamentals/1-4-AnalysisOfAlgorithms/ThreeSumFast.java:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 | * Compilation: javac ThreeSumFast.java
3 | * Execution: java ThreeSumFast input.txt
4 | * Data files: http://algs4.cs.princeton.edu/14analysis/1Kints.txt
5 | * http://algs4.cs.princeton.edu/14analysis/2Kints.txt
6 | * http://algs4.cs.princeton.edu/14analysis/4Kints.txt
7 | * http://algs4.cs.princeton.edu/14analysis/8Kints.txt
8 | * http://algs4.cs.princeton.edu/14analysis/16Kints.txt
9 | * http://algs4.cs.princeton.edu/14analysis/32Kints.txt
10 | * http://algs4.cs.princeton.edu/14analysis/1Mints.txt
11 | *
12 | * A program with N^2 log N running time. Read in N integers
13 | * and counts the number of triples that sum to exactly 0.
14 | *
15 | * Limitations
16 | * -----------
17 | * - we ignore integer overflow
18 | * - doesn't handle case when input has duplicates
19 | *
20 | *
21 | * % java ThreeSumFast 1Kints.txt
22 | * 70
23 | *
24 | * % java ThreeSumFast 2Kints.txt
25 | * 528
26 | *
27 | * % java ThreeSumFast 4Kints.txt
28 | * 4039
29 | *
30 | * % java ThreeSumFast 8Kints.txt
31 | * 32074
32 | *
33 | * % java ThreeSumFast 16Kints.txt
34 | * 255181
35 | *
36 | * % java ThreeSumFast 32Kints.txt
37 | * 2052358
38 | *
39 | *************************************************************************/
40 |
41 | import java.util.Arrays;
42 |
43 | public class ThreeSumFast {
44 |
45 | // print distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0
46 | public static void printAll(int[] a) {
47 | int N = a.length;
48 | Arrays.sort(a);
49 | for (int i = 0; i < N; i++) {
50 | for (int j = i+1; j < N; j++) {
51 | int k = Arrays.binarySearch(a, -(a[i] + a[j]));
52 | if (k > j) StdOut.println(a[i] + " " + a[j] + " " + a[k]);
53 | }
54 | }
55 | }
56 |
57 | // return number of distinct triples (i, j, k) such that a[i] + a[j] + a[k] = 0
58 | public static int count(int[] a) {
59 | int N = a.length;
60 | Arrays.sort(a);
61 | int cnt = 0;
62 | for (int i = 0; i < N; i++) {
63 | for (int j = i+1; j < N; j++) {
64 | int k = Arrays.binarySearch(a, -(a[i] + a[j]));
65 | if (k > j) cnt++;
66 | }
67 | }
68 | return cnt;
69 | }
70 |
71 | public static void main(String[] args) {
72 | int[] a = In.readInts(args[0]);
73 | int cnt = count(a);
74 | StdOut.println(cnt);
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/1-Fundamentals/1-5-UnionFind/QuickFindUF.java:
--------------------------------------------------------------------------------
1 | /****************************************************************************
2 | * Compilation: javac QuickFindUF.java
3 | * Execution: java QuickFindUF < input.txt
4 | * Dependencies: StdIn.java StdOut.java
5 | *
6 | * Quick-find algorithm.
7 | *
8 | ****************************************************************************/
9 |
10 | public class QuickFindUF {
11 | private int[] id;
12 | private int count;
13 |
14 | // instantiate N isolated components 0 through N-1
15 | public QuickFindUF(int N) {
16 | count = N;
17 | id = new int[N];
18 | for (int i = 0; i < N; i++)
19 | id[i] = i;
20 | }
21 |
22 | // return number of connected components
23 | public int count() {
24 | return count;
25 | }
26 |
27 | // Return component identifier for component containing p
28 | public int find(int p) {
29 | return id[p];
30 | }
31 |
32 | // are elements p and q in the same component?
33 | public boolean connected(int p, int q) {
34 | return id[p] == id[q];
35 | }
36 |
37 | // merge components containing p and q
38 | public void union(int p, int q) {
39 | if (connected(p, q)) return;
40 | int pid = id[p];
41 | for (int i = 0; i < id.length; i++)
42 | if (id[i] == pid) id[i] = id[q];
43 | count--;
44 | }
45 |
46 | public static void main(String[] args) {
47 | int N = StdIn.readInt();
48 | QuickFindUF uf = new QuickFindUF(N);
49 |
50 | // read in a sequence of pairs of integers (each in the range 0 to N-1),
51 | // calling find() for each pair: If the members of the pair are not already
52 | // call union() and print the pair.
53 | while (!StdIn.isEmpty()) {
54 | int p = StdIn.readInt();
55 | int q = StdIn.readInt();
56 | if (uf.connected(p, q)) continue;
57 | uf.union(p, q);
58 | StdOut.println(p + " " + q);
59 | }
60 | StdOut.println("# components: " + uf.count());
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/1-Fundamentals/1-5-UnionFind/QuickUnionUF.java:
--------------------------------------------------------------------------------
1 | /****************************************************************************
2 | * Compilation: javac QuickUnionUF.java
3 | * Execution: java QuickUnionUF < input.txt
4 | * Dependencies: StdIn.java StdOut.java
5 | *
6 | * Quick-union algorithm.
7 | *
8 | ****************************************************************************/
9 |
10 | public class QuickUnionUF {
11 | private int[] id; // id[i] = parent of i
12 | private int count; // number of components
13 |
14 | // instantiate N isolated components 0 through N-1
15 | public QuickUnionUF(int N) {
16 | id = new int[N];
17 | count = N;
18 | for (int i = 0; i < N; i++) {
19 | id[i] = i;
20 | }
21 | }
22 |
23 | // return number of connected components
24 | public int count() {
25 | return count;
26 | }
27 |
28 | // return root of component corresponding to element p
29 | public int find(int p) {
30 | while (p != id[p])
31 | p = id[p];
32 | return p;
33 | }
34 |
35 | // are elements p and q in the same component?
36 | public boolean connected(int p, int q) {
37 | return find(p) == find(q);
38 | }
39 |
40 | // merge components containing p and q
41 | public void union(int p, int q) {
42 | int i = find(p);
43 | int j = find(q);
44 | if (i == j) return;
45 | id[i] = j;
46 | count--;
47 | }
48 |
49 | public static void main(String[] args) {
50 | int N = StdIn.readInt();
51 | QuickUnionUF uf = new QuickUnionUF(N);
52 |
53 | // read in a sequence of pairs of integers (each in the range 0 to N-1),
54 | // calling find() for each pair: If the members of the pair are not already
55 | // call union() and print the pair.
56 | while (!StdIn.isEmpty()) {
57 | int p = StdIn.readInt();
58 | int q = StdIn.readInt();
59 | if (uf.connected(p, q)) continue;
60 | uf.union(p, q);
61 | StdOut.println(p + " " + q);
62 | }
63 | StdOut.println("# components: " + uf.count());
64 | }
65 |
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/1-Fundamentals/1-5-UnionFind/WeightedQuickUnionUF.java:
--------------------------------------------------------------------------------
1 | /****************************************************************************
2 | * Compilation: javac WeightedQuickUnionUF.java
3 | * Execution: java WeightedQuickUnionUF < input.txt
4 | * Dependencies: StdIn.java StdOut.java
5 | *
6 | * Weighted quick-union (without path compression).
7 | *
8 | ****************************************************************************/
9 |
10 | public class WeightedQuickUnionUF {
11 | private int[] id; // id[i] = parent of i
12 | private int[] sz; // sz[i] = number of objects in subtree rooted at i
13 | private int count; // number of components
14 |
15 | // Create an empty union find data structure with N isolated sets.
16 | public WeightedQuickUnionUF(int N) {
17 | count = N;
18 | id = new int[N];
19 | sz = new int[N];
20 | for (int i = 0; i < N; i++) {
21 | id[i] = i;
22 | sz[i] = 1;
23 | }
24 | }
25 |
26 | // Return the number of disjoint sets.
27 | public int count() {
28 | return count;
29 | }
30 |
31 | // Return component identifier for component containing p
32 | public int find(int p) {
33 | while (p != id[p])
34 | p = id[p];
35 | return p;
36 | }
37 |
38 | // Are objects p and q in the same set?
39 | public boolean connected(int p, int q) {
40 | return find(p) == find(q);
41 | }
42 |
43 |
44 | // Replace sets containing p and q with their union.
45 | public void union(int p, int q) {
46 | int i = find(p);
47 | int j = find(q);
48 | if (i == j) return;
49 |
50 | // make smaller root point to larger one
51 | if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; }
52 | else { id[j] = i; sz[i] += sz[j]; }
53 | count--;
54 | }
55 |
56 |
57 | public static void main(String[] args) {
58 | int N = StdIn.readInt();
59 | WeightedQuickUnionUF uf = new WeightedQuickUnionUF(N);
60 |
61 | // read in a sequence of pairs of integers (each in the range 0 to N-1),
62 | // calling find() for each pair: If the members of the pair are not already
63 | // call union() and print the pair.
64 | while (!StdIn.isEmpty()) {
65 | int p = StdIn.readInt();
66 | int q = StdIn.readInt();
67 | if (uf.connected(p, q)) continue;
68 | uf.union(p, q);
69 | StdOut.println(p + " " + q);
70 | }
71 | StdOut.println("# components: " + uf.count());
72 | }
73 |
74 | }
75 |
76 |
--------------------------------------------------------------------------------
/1-Fundamentals/1-5-UnionFind/tinyUF.txt:
--------------------------------------------------------------------------------
1 | 10
2 | 4 3
3 | 3 8
4 | 6 5
5 | 9 4
6 | 2 1
7 | 8 9
8 | 5 0
9 | 7 2
10 | 6 1
11 | 1 0
12 | 6 7
13 |
--------------------------------------------------------------------------------
/2-Sorting/2-1-ElementarySorts/tiny.txt:
--------------------------------------------------------------------------------
1 | S O R T E X A M P L E
2 |
--------------------------------------------------------------------------------
/2-Sorting/2-1-ElementarySorts/words3.txt:
--------------------------------------------------------------------------------
1 | bed bug dad yes zoo
2 | now for tip ilk dim
3 | tag jot sob nob sky
4 | hut men egg few jay
5 | owl joy rap gig wee
6 | was wad fee tap tar
7 | dug jam all bad yet
8 |
--------------------------------------------------------------------------------
/2-Sorting/2-2-Mergesort/tiny.txt:
--------------------------------------------------------------------------------
1 | S O R T E X A M P L E
2 |
--------------------------------------------------------------------------------
/2-Sorting/2-2-Mergesort/words3.txt:
--------------------------------------------------------------------------------
1 | bed bug dad yes zoo
2 | now for tip ilk dim
3 | tag jot sob nob sky
4 | hut men egg few jay
5 | owl joy rap gig wee
6 | was wad fee tap tar
7 | dug jam all bad yet
8 |
--------------------------------------------------------------------------------
/2-Sorting/2-3-Quicksort/tiny.txt:
--------------------------------------------------------------------------------
1 | S O R T E X A M P L E
2 |
--------------------------------------------------------------------------------
/2-Sorting/2-3-Quicksort/words3.txt:
--------------------------------------------------------------------------------
1 | bed bug dad yes zoo
2 | now for tip ilk dim
3 | tag jot sob nob sky
4 | hut men egg few jay
5 | owl joy rap gig wee
6 | was wad fee tap tar
7 | dug jam all bad yet
8 |
--------------------------------------------------------------------------------
/2-Sorting/2-4-PriorityQueues/Heap.java:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 | * Compilation: javac Heap.java
3 | * Execution: java Heap < input.txt
4 | * Dependencies: StdOut.java StdIn.java
5 | * Data files: http://algs4.cs.princeton.edu/24pq/tiny.txt
6 | * http://algs4.cs.princeton.edu/24pq/words3.txt
7 | *
8 | * Sorts a sequence of strings from standard input using heapsort.
9 | *
10 | * % more tiny.txt
11 | * S O R T E X A M P L E
12 | *
13 | * % java Heap < tiny.txt
14 | * S O R T E X A M P L E A [ one string per line ]
15 | *
16 | * % more words3.txt
17 | * bed bug dad yes zoo ... all bad yet
18 | *
19 | * % java Heap < words3.txt
20 | * all bad bed bug dad ... yes yet zoo [ one string per line ]
21 | *
22 | *************************************************************************/
23 |
24 | public class Heap {
25 |
26 | public static void sort(Comparable[] pq) {
27 | int N = pq.length;
28 | for (int k = N/2; k >= 1; k--)
29 | sink(pq, k, N);
30 | while (N > 1) {
31 | exch(pq, 1, N--);
32 | sink(pq, 1, N);
33 | }
34 | }
35 |
36 | /***********************************************************************
37 | * Helper functions to restore the heap invariant.
38 | **********************************************************************/
39 |
40 | private static void sink(Comparable[] pq, int k, int N) {
41 | while (2*k <= N) {
42 | int j = 2*k;
43 | if (j < N && less(pq, j, j+1)) j++;
44 | if (!less(pq, k, j)) break;
45 | exch(pq, k, j);
46 | k = j;
47 | }
48 | }
49 |
50 | /***********************************************************************
51 | * Helper functions for comparisons and swaps.
52 | * Indices are "off-by-one" to support 1-based indexing.
53 | **********************************************************************/
54 | private static boolean less(Comparable[] pq, int i, int j) {
55 | return pq[i-1].compareTo(pq[j-1]) < 0;
56 | }
57 |
58 | private static void exch(Object[] pq, int i, int j) {
59 | Object swap = pq[i-1];
60 | pq[i-1] = pq[j-1];
61 | pq[j-1] = swap;
62 | }
63 |
64 | // is v < w ?
65 | private static boolean less(Comparable v, Comparable w) {
66 | return (v.compareTo(w) < 0);
67 | }
68 |
69 |
70 | /***********************************************************************
71 | * Check if array is sorted - useful for debugging
72 | ***********************************************************************/
73 | private static boolean isSorted(Comparable[] a) {
74 | for (int i = 1; i < a.length; i++)
75 | if (less(a[i], a[i-1])) return false;
76 | return true;
77 | }
78 |
79 |
80 | // print array to standard output
81 | private static void show(Comparable[] a) {
82 | for (int i = 0; i < a.length; i++) {
83 | StdOut.println(a[i]);
84 | }
85 | }
86 |
87 | // Read strings from standard input, sort them, and print.
88 | public static void main(String[] args) {
89 | String[] a = StdIn.readStrings();
90 | Heap.sort(a);
91 | show(a);
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/2-Sorting/2-4-PriorityQueues/Multiway.java:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 | * Compilation: javac Multiway.java
3 | * Execution: java Multiway input1.txt input2.txt input3.txt ...
4 | * Dependencies: IndexMinPQ.java In.java StdOut.java
5 | *
6 | * Merges together the sorted input stream given as command-line arguments
7 | * into a single sorted output stream on standard output.
8 | *
9 | * % more m1.txt
10 | * A B C F G I I Z
11 | *
12 | * % more m2.txt
13 | * B D H P Q Q
14 | *
15 | * % more m3.txt
16 | * A B E F J N
17 | *
18 | * % java Multiway m1.txt m2.txt m3.txt
19 | * A A B B B C D E F F G H I I J N P Q Q Z
20 | *
21 | *************************************************************************/
22 |
23 | public class Multiway {
24 |
25 | public static void merge(In[] streams) {
26 | int N = streams.length;
27 | IndexMinPQ
12 | * For additional documentation, see Section 4.3 of
13 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
14 | */
15 | public class Edge implements Comparable
12 | * For additional documentation, see Section 4.4 of
13 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
14 | */
15 |
16 | public class DirectedEdge {
17 | private final int v;
18 | private final int w;
19 | private final double weight;
20 |
21 | /**
22 | * Create a directed edge from v to w with given weight.
23 | */
24 | public DirectedEdge(int v, int w, double weight) {
25 | this.v = v;
26 | this.w = w;
27 | this.weight = weight;
28 | }
29 |
30 | /**
31 | * Return the vertex where this edge begins.
32 | */
33 | public int from() {
34 | return v;
35 | }
36 |
37 | /**
38 | * Return the vertex where this edge ends.
39 | */
40 | public int to() {
41 | return w;
42 | }
43 |
44 | /**
45 | * Return the weight of this edge.
46 | */
47 | public double weight() { return weight; }
48 |
49 | /**
50 | * Return a string representation of this edge.
51 | */
52 | public String toString() {
53 | return v + "->" + w + " " + String.format("%5.2f", weight);
54 | }
55 |
56 | /**
57 | * Test client.
58 | */
59 | public static void main(String[] args) {
60 | DirectedEdge e = new DirectedEdge(12, 23, 3.14);
61 | StdOut.println(e);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/4-Graphs/4-4-ShortestPaths/jobsPC.txt:
--------------------------------------------------------------------------------
1 | 10
2 | 41.0 3 1 7 9
3 | 51.0 1 2
4 | 50.0 0
5 | 36.0 0
6 | 38.0 0
7 | 45.0 0
8 | 21.0 2 3 8
9 | 32.0 2 3 8
10 | 32.0 1 2
11 | 29.0 2 4 6
12 |
--------------------------------------------------------------------------------
/4-Graphs/4-4-ShortestPaths/rates.txt:
--------------------------------------------------------------------------------
1 | 5
2 | USD 1 0.741 0.657 1.061 1.005
3 | EUR 1.349 1 0.888 1.433 1.366
4 | GBP 1.521 1.126 1 1.614 1.538
5 | CHF 0.942 0.698 0.619 1 0.953
6 | CAD 0.995 0.732 0.650 1.049 1
7 |
8 |
--------------------------------------------------------------------------------
/4-Graphs/4-4-ShortestPaths/tinyEWD.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
18 |
--------------------------------------------------------------------------------
/4-Graphs/4-4-ShortestPaths/tinyEWDAG.txt:
--------------------------------------------------------------------------------
1 | 8
2 | 13
3 | 5 4 0.35
4 | 4 7 0.37
5 | 5 7 0.28
6 | 5 1 0.32
7 | 4 0 0.38
8 | 0 2 0.26
9 | 3 7 0.39
10 | 1 3 0.29
11 | 7 2 0.34
12 | 6 2 0.40
13 | 3 6 0.52
14 | 6 0 0.58
15 | 6 4 0.93
16 |
--------------------------------------------------------------------------------
/4-Graphs/4-4-ShortestPaths/tinyEWDn.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 -1.20
15 | 3 6 0.52
16 | 6 0 -1.40
17 | 6 4 -1.25
18 |
--------------------------------------------------------------------------------
/4-Graphs/4-4-ShortestPaths/tinyEWDnc.txt:
--------------------------------------------------------------------------------
1 | 8
2 | 15
3 | 4 5 0.35
4 | 5 4 -0.66
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
18 |
--------------------------------------------------------------------------------
/5-Strings/5-1-StringSorts/LSD.java:
--------------------------------------------------------------------------------
1 | /***********************************************************************************
2 | * Compilation: javac LSD.java
3 | * Execution: java LSD < input.txt
4 | *
5 | * LSD radix sort an array of extended ASCII strings, each of length W.
6 | *
7 | * % java LSD < words3.txt
8 | * all
9 | * bad
10 | * bed
11 | * bug
12 | * dad
13 | * ...
14 | * yes
15 | * yet
16 | * zoo
17 | *
18 | ***********************************************************************************/
19 |
20 | public class LSD {
21 |
22 | // LSD radix sort
23 | public static void sort(String[] a, int W) {
24 | int N = a.length;
25 | int R = 256; // extend ASCII alphabet size
26 | String[] aux = new String[N];
27 |
28 | for (int d = W-1; d >= 0; d--) {
29 | // sort by key-indexed counting on dth character
30 |
31 | // compute frequency counts
32 | int[] count = new int[R+1];
33 | for (int i = 0; i < N; i++)
34 | count[a[i].charAt(d) + 1]++;
35 |
36 | // compute cumulates
37 | for (int r = 0; r < R; r++)
38 | count[r+1] += count[r];
39 |
40 | // move data
41 | for (int i = 0; i < N; i++)
42 | aux[count[a[i].charAt(d)]++] = a[i];
43 |
44 | // copy back
45 | for (int i = 0; i < N; i++)
46 | a[i] = aux[i];
47 | }
48 | }
49 |
50 |
51 | public static void main(String[] args) {
52 | String[] a = StdIn.readStrings();
53 | int N = a.length;
54 |
55 | // check that strings have fixed length
56 | int W = a[0].length();
57 | for (int i = 0; i < N; i++)
58 | assert a[i].length() == W : "Strings must have fixed length";
59 |
60 | // sort the strings
61 | sort(a, W);
62 |
63 | // print results
64 | for (int i = 0; i < N; i++)
65 | StdOut.println(a[i]);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/5-Strings/5-1-StringSorts/MSD.java:
--------------------------------------------------------------------------------
1 | /***********************************************************************************
2 | * Compilation: javac MSD.java
3 | * Execution: java MSD < input.txt
4 | *
5 | * Reads extended ASCII string from standard input and MSD radix sorts them.
6 | *
7 | * % java MSD < shells.txt
8 | * are
9 | * by
10 | * sea
11 | * seashells
12 | * seashells
13 | * sells
14 | * sells
15 | * she
16 | * she
17 | * shells
18 | * shore
19 | * surely
20 | * the
21 | * the
22 | *
23 | ***********************************************************************************/
24 |
25 | public class MSD {
26 | private static final int R = 256; // extended ASCII alphabet size
27 | private static final int CUTOFF = 15; // cutoff to insertion sort
28 |
29 | // sort array of strings
30 | public static void sort(String[] a) {
31 | int N = a.length;
32 | String[] aux = new String[N];
33 | sort(a, 0, N-1, 0, aux);
34 | }
35 |
36 | // return dth character of s, -1 if d = length of string
37 | private static int charAt(String s, int d) {
38 | assert d >= 0 && d <= s.length();
39 | if (d == s.length()) return -1;
40 | return s.charAt(d);
41 | }
42 |
43 | // sort from a[lo] to a[hi], starting at the dth character
44 | private static void sort(String[] a, int lo, int hi, int d, String[] aux) {
45 |
46 | // cutoff to insertion sort for small subarrays
47 | if (hi <= lo + CUTOFF) {
48 | insertion(a, lo, hi, d);
49 | return;
50 | }
51 |
52 | // compute frequency counts
53 | int[] count = new int[R+2];
54 | for (int i = lo; i <= hi; i++) {
55 | int c = charAt(a[i], d);
56 | count[c+2]++;
57 | }
58 |
59 | // transform counts to indicies
60 | for (int r = 0; r < R+1; r++)
61 | count[r+1] += count[r];
62 |
63 | // distribute
64 | for (int i = lo; i <= hi; i++) {
65 | int c = charAt(a[i], d);
66 | aux[count[c+1]++] = a[i];
67 | }
68 |
69 | // copy back
70 | for (int i = lo; i <= hi; i++)
71 | a[i] = aux[i - lo];
72 |
73 |
74 | // recursively sort for each character
75 | for (int r = 0; r < R; r++)
76 | sort(a, lo + count[r], lo + count[r+1] - 1, d+1, aux);
77 | }
78 |
79 |
80 | // return dth character of s, -1 if d = length of string
81 | private static void insertion(String[] a, int lo, int hi, int d) {
82 | for (int i = lo; i <= hi; i++)
83 | for (int j = i; j > lo && less(a[j], a[j-1], d); j--)
84 | exch(a, j, j-1);
85 | }
86 |
87 | // exchange a[i] and a[j]
88 | private static void exch(String[] a, int i, int j) {
89 | String temp = a[i];
90 | a[i] = a[j];
91 | a[j] = temp;
92 | }
93 |
94 | // is v less than w, starting at character d
95 | private static boolean less(String v, String w, int d) {
96 | assert v.substring(0, d).equals(w.substring(0, d));
97 | return v.substring(d).compareTo(w.substring(d)) < 0;
98 | }
99 |
100 |
101 | public static void main(String[] args) {
102 | String[] a = StdIn.readStrings();
103 | int N = a.length;
104 | sort(a);
105 | for (int i = 0; i < N; i++)
106 | StdOut.println(a[i]);
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/5-Strings/5-1-StringSorts/shells.txt:
--------------------------------------------------------------------------------
1 | she sells seashells by the sea shore
2 | the shells she sells are surely seashells
3 |
--------------------------------------------------------------------------------
/5-Strings/5-1-StringSorts/words3.txt:
--------------------------------------------------------------------------------
1 | bed bug dad yes zoo
2 | now for tip ilk dim
3 | tag jot sob nob sky
4 | hut men egg few jay
5 | owl joy rap gig wee
6 | was wad fee tap tar
7 | dug jam all bad yet
8 |
--------------------------------------------------------------------------------
/5-Strings/5-2-Tries/shellsST.txt:
--------------------------------------------------------------------------------
1 | she sells sea shells by the sea shore
2 |
--------------------------------------------------------------------------------
/5-Strings/5-4-RegularExpressions/GREP.java:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 | * Compilation: javac GREP.java
3 | * Execution: java GREP regexp < input.txt
4 | * Dependencies: NFA.java
5 | * Data files: http://algs4.cs.princeton.edu/54regexp/tinyL.txt
6 | *
7 | * This program takes an RE as a command-line argument and prints
8 | * the lines from standard input having some substring that
9 | * is in the language described by the RE.
10 | *
11 | * % more tinyL.txt
12 | * AC
13 | * AD
14 | * AAA
15 | * ABD
16 | * ADD
17 | * BCD
18 | * ABCCBD
19 | * BABAAA
20 | * BABBAAA
21 | *
22 | * % java GREP "(A*B|AC)D" < tinyL.txt
23 | * ABD
24 | * ABCCBD
25 | *
26 | *************************************************************************/
27 |
28 | public class GREP {
29 | public static void main(String[] args) {
30 | String regexp = "(.*" + args[0] + ".*)";
31 | NFA nfa = new NFA(regexp);
32 | while (StdIn.hasNextLine()) {
33 | String txt = StdIn.readLine();
34 | if (nfa.recognizes(txt)) {
35 | StdOut.println(txt);
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/5-Strings/5-4-RegularExpressions/NFA.java:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 | * Compilation: javac NFA.java
3 | * Execution: java NFA regexp text
4 | * Dependencies: Stack.java Bag.java Digraph.java DirectedDFS.java
5 | *
6 | * % java NFA "(A*B|AC)D" AAAABD
7 | * true
8 | *
9 | * % java NFA "(A*B|AC)D" AAAAC
10 | * false
11 | *
12 | * % java NFA "(a|(bc)*d)*" abcbcd
13 | * true
14 | *
15 | * % java NFA "(a|(bc)*d)*" abcbcbcdaaaabcbcdaaaddd
16 | * true
17 | *
18 | *************************************************************************/
19 |
20 | public class NFA {
21 |
22 | private Digraph G; // digraph of epsilon transitions
23 | private String regexp; // regular expression
24 | private int M; // number of characters in regular expression
25 |
26 | // Create the NFA for the given RE
27 | public NFA(String regexp) {
28 | this.regexp = regexp;
29 | M = regexp.length();
30 | Stack
13 | * For additional documentation, see Section 7.4 of
14 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
15 | */
16 |
17 |
18 | public class FlowEdge {
19 | private final int v; // from
20 | private final int w; // to
21 | private final double capacity; // capacity
22 | private double flow; // flow
23 |
24 | public FlowEdge(int v, int w, double capacity) {
25 | if (capacity < 0) throw new RuntimeException("Negative edge capacity");
26 | this.v = v;
27 | this.w = w;
28 | this.capacity = capacity;
29 | this.flow = 0;
30 | }
31 |
32 | public FlowEdge(int v, int w, double capacity, double flow) {
33 | if (capacity < 0) throw new RuntimeException("Negative edge capacity");
34 | this.v = v;
35 | this.w = w;
36 | this.capacity = capacity;
37 | this.flow = flow;
38 | }
39 |
40 | // accessor methods
41 | public int from() { return v; }
42 | public int to() { return w; }
43 | public double capacity() { return capacity; }
44 | public double flow() { return flow; }
45 |
46 |
47 | public int other(int vertex) {
48 | if (vertex == v) return w;
49 | else if (vertex == w) return v;
50 | else throw new RuntimeException("Illegal endpoint");
51 | }
52 |
53 | public double residualCapacityTo(int vertex) {
54 | if (vertex == v) return flow;
55 | else if (vertex == w) return capacity - flow;
56 | else throw new RuntimeException("Illegal endpoint");
57 | }
58 |
59 | public void addResidualFlowTo(int vertex, double delta) {
60 | if (vertex == v) flow -= delta;
61 | else if (vertex == w) flow += delta;
62 | else throw new RuntimeException("Illegal endpoint");
63 | }
64 |
65 |
66 | public String toString() {
67 | return v + "->" + w + " " + flow + "/" + capacity;
68 | }
69 |
70 |
71 | /**
72 | * Test client.
73 | */
74 | public static void main(String[] args) {
75 | FlowEdge e = new FlowEdge(12, 23, 3.14);
76 | StdOut.println(e);
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/6-Context/6-4-Maxflow/FlowNetwork.java:
--------------------------------------------------------------------------------
1 | /*************************************************************************
2 | * Compilation: javac FlowNetwork.java
3 | * Execution: java FlowNetwork V E
4 | * Dependencies: Bag.java FlowEdge.java
5 | *
6 | * A capacitated flow network, implemented using adjacency lists.
7 | *
8 | *************************************************************************/
9 |
10 | public class FlowNetwork {
11 | private final int V;
12 | private int E;
13 | private Bag
11 | * For additional documentation, see
12 | * Section 3.2 of
13 | * Introduction to Programming in Java: An Interdisciplinary Approach
14 | * by Robert Sedgewick and Kevin Wayne.
15 | */
16 |
17 |
18 |
19 | public class Stopwatch {
20 |
21 | private final long start;
22 |
23 | /**
24 | * Create a stopwatch object.
25 | */
26 | public Stopwatch() {
27 | start = System.currentTimeMillis();
28 | }
29 |
30 |
31 | /**
32 | * Return elapsed time (in seconds) since this object was created.
33 | */
34 | public double elapsedTime() {
35 | long now = System.currentTimeMillis();
36 | return (now - start) / 1000.0;
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/StdLib/mandrill.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/StdLib/mandrill.jpg
--------------------------------------------------------------------------------
/algs4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/algs4.jar
--------------------------------------------------------------------------------
/stdlib.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aistrate/AlgorithmsSedgewick/06703c1371ffdf669d3996baa9e9684d13cdcc82/stdlib.jar
--------------------------------------------------------------------------------