question
stringlengths
34
5.53k
answer
stringlengths
21
101k
support_files
listlengths
0
6
metadata
unknown
Write a program to determine the number pairs of values in an input file that are equal. If your first try is quadratic, think again and use Arrays.sort() to develop a linearithmic solution.
package chapter1.section4; import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Created by Rene Argento on 9/28/16. */ // Thanks to Vivek Bhojawala (https://github.com/VBhojawala) for mentioning that the solution shou...
[]
{ "number": "1.4.8", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false }
Modify binary search so that it always returns the element with the smallest index that matches the search element (and still guarantees logarithmic running time).
package chapter1.section4; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 9/28/16. */ // Thanks to Vivek Bhojawala (https://github.com/VBhojawala) for fixing a bug and suggesting improvements // in the binarySearch() method at https://github.com/reneargento/algorithms-sedgewick-wayne/issues/...
[]
{ "number": "1.4.10", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false }
Write a program that, given two sorted arrays of N int values, prints all elements that appear in both arrays, in sorted order. The running time of your program should be proportional to N in the worst case.
package chapter1.section4; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 9/29/16. */ // Thanks to ektasingh151 (https://github.com/ektasingh151) for suggesting a simpler solution: // https://github.com/reneargento/algorithms-sedgewick-wayne/pull/149 public class Exercise12 { public sta...
[]
{ "number": "1.4.12", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Exercise", "code_execution": false }
Closest pair (in one dimension). Write a program that, given an array a[] of N double values, finds a closest pair: two values whose difference is no greater than the difference of any other pair (in absolute value). The running time of your program should be linearithmic in the worst case.
package chapter1.section4; import edu.princeton.cs.algs4.StdOut; import java.util.Arrays; /** * Created by Rene Argento on 9/30/16. */ public class Exercise16_ClosestPair { public static void main(String[] args) { double[] array1 = {-5.2, 9.4, 20, -10, 21.1, 40, 50, -20}; double[] array2 = {-4...
[]
{ "number": "1.4.16", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Farthest pair (in one dimension). Write a program that, given an array a[] of N double values, finds a farthest pair: two values whose difference is no smaller than the difference of any other pair (in absolute value). The running time of your program should be linear in the worst case.
package chapter1.section4; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 9/30/16. */ public class Exercise17_FarthestPair { public static void main(String[] args) { double[] array1 = {-5.2, 9.4, 20, -10, 21.1, 40, 50, -20}; double[] array2 = {-4, -3, 0, 10, 20}; ...
[]
{ "number": "1.4.17", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Local minimum of an array. Write a program that, given an array a[] of N distinct integers, finds a local minimum: an index i such that a[i] is smaller than its neighbors (a[i-1] > a[i] < a[i+1]). Your program should use ~2lg N compares in the worst case.
public static int localMinimumIndex(int[] a) { if (a == null || a.length == 0) return -1; if (a.length == 1 || a[0] < a[1]) return 0; int n = a.length; if (a[n - 1] < a[n - 2]) return n - 1; int lo = 1; int hi = n - 2; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[m...
[]
{ "number": "1.4.18", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Local minimum of a matrix. Given an N-by-N array a[] of N^2 distinct integers, design an algorithm that runs in time proportional to N to find a local minimum: a pair of indices i and j such that a[i][j] < a[i+1][j], a[i][j] < a[i][j+1], a[i][j] < a[i-1][j], and a[i][j] < a[i][j-1]. The running time of your program sho...
Use the standard divide-and-conquer algorithm: inspect the middle row and middle column, find the minimum item on that cross, and either return it if it is smaller than its four neighbors or recurse into the quadrant containing a smaller neighbor. ```java public static int[] localMinimum(int[][] a) { return localM...
[]
{ "number": "1.4.19", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Throwing two eggs from a building. Consider the previous question, but now suppose you only have two eggs, and your cost model is the number of throws. Devise a strategy to determine F such that the number of throws is at most 2√N, then find a way to reduce the cost to ~c√F. This is analogous to a situation where searc...
package chapter1.section4; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 23/10/16. */ public class Exercise25_Throwing2Eggs { public static void main(String[] args) { int[] array = {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
[]
{ "number": "1.4.25", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Queue with two stacks. Implement a queue with two stacks so that each queue operation takes a constant amortized number of stack operations. Hint: If you push elements onto a stack and then pop them all, they appear in reverse order. If you repeat this process, they’re now back in order.
package chapter1.section4; import edu.princeton.cs.algs4.StdOut; import java.util.Stack; /** * Created by Rene Argento on 20/11/16. */ public class Exercise27_QueueWith2Stacks<Item> { private Stack<Item> tailStack; private Stack<Item> headStack; public Exercise27_QueueWith2Stacks() { tailStack...
[]
{ "number": "1.4.27", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Hot or cold. Your goal is to guess a secret integer between 1 and N. You repeatedly guess integers between 1 and N. After each guess you learn if your guess equals the secret integer (and the game stops). Otherwise, you learn if the guess is hotter (closer to) or colder (farther from) the secret number than your previo...
// Exercise34_HotOrCold1LgN.java package chapter1.section4; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 23/11/16. */ //IOI 2010 task //Based on http://stackoverflow.com/questions/25558951/hot-and-cold-binary-search-game // Worst case is O(lg n) + 6 when we start in an "end quarter" ...
[]
{ "number": "1.4.34", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Time costs for pushdown stacks. Justify the entries in the table below, which shows typical time costs for various pushdown stack implementations, using a cost model that counts both data references (references to data pushed onto the stack, either an array reference or a reference to an object’s instance variable) and...
1.4.35 - Time costs for pushdown stacks ** Linked list * int 2N data references - N references of the nodes for the enclosing class and N references for the next Node (including a reference to the first node in the stack) N objects created - the N nodes created * Integer 3N data references - N refer...
[]
{ "number": "1.4.35", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Creative Problem", "code_execution": false }
Naive 3-sum implementation. Run experiments to evaluate the following implementation of the inner loop of ThreeSum: for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) if (i < j && j < k) if (a[i] + a[j] + a[k] == 0) cnt++; Do so by developing a version of DoublingTest that computes...
// Exercise38_Naive3Sum.java package chapter1.section4; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.Stopwatch; import java.util.HashMap; import java.util.Map; /** * Created by Rene Argento on 26/11/16. */ public class Exercise38_Naive3Sum { priv...
[]
{ "number": "1.4.38", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.4, "section_title": "Analysis of Algorithms", "type": "Experiment", "code_execution": false }
Show the contents of the id[] array and the number of times the array is accessed for each input pair when you use quick-find for the sequence 9-0 3-4 5-8 7-2 2-1 5-7 0-3 4-2.
1.5.1 0 1 2 3 4 5 6 7 8 9 array = 0 1 2 3 4 5 6 7 8 9 9-0 0 1 2 3 4 5 6 7 8 9 array = 0 1 2 3 4 5 6 7 8 0 Array accesses: 13 (2 in 2x find() + 10 for checking parents + 1 for updating parents) 3-4 0 1 2 3 4 5 6 7 8 9 array = 0 1 2 4 4 5 6 7 8 0 Array accesses: 13 (2 in 2x find() + 10 for check...
[]
{ "number": "1.5.1", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false }
Do Exercise 1.5.1, but use quick-union (page 224). In addition, draw the forest of trees represented by the id[] array after each input pair is processed.
1.5.2 0 1 2 3 4 5 6 7 8 9 array = 0 1 2 3 4 5 6 7 8 9 9-0 0 1 2 3 4 5 6 7 8 9 array = 0 1 2 3 4 5 6 7 8 0 Array accesses: 3 (1 for find(9), 1 for find(0) and 1 for updating parent) Forest: 0 1 2 3 4 5 6 7 8 9 3-4 0 1 2 3 4 5 6 7 8 9 array = 0 1 2 4 4 5 6 7 8 0 Array accesses: 3 (1 for find(3...
[]
{ "number": "1.5.2", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false }
Show the contents of the sz[] and id[] arrays and the number of array accesses for each input pair corresponding to the weighted quick-union examples in the text (both the reference input and the worst-case input).
1.5.4 Reference input Beginning id[] 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 sz[] 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 4-3 id[] 0 1 2 3 4 5 6 7 8 9 0 1 2 4 4 5 6 7 8 9 sz[] 0 1 2 3 4 5 6 7 8 9 1 1 1 1 2 1 1 1 1 1 Array accesses: 3 (1 for find(4), 1 for find(3) and 1 for updating parent) 3-8 id[] 0 1 2 3 4 ...
[]
{ "number": "1.5.4", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false }
Repeat Exercise 1.5.5 for weighted quick-union.
1.5.6 10^9 sites 10^6 input pairs Computer can execute 10^9 instructions per second Each iteration of the inner for loop requires 10 instructions The object initialization makes ~10^10 instructions (1 for initializing the count variable, 1 for creating the sites array, 10^10 due to the for loop iterations over the si...
[]
{ "number": "1.5.6", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false }
Develop classes QuickUnionUF and QuickFindUF that implement quick-union and quick-find, respectively.
```java public class QuickUnionUF { private final int[] parent; private int count; public QuickUnionUF(int n) { count = n; parent = new int[n]; for (int i = 0; i < n; i++) parent[i] = i; } public int count() { return count; } public int find(int p) { while (p !...
[]
{ "number": "1.5.7", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false }
Give a counterexample that shows why this intuitive implementation of union() for quick-find is not correct: public void union(int p, int q) { if (connected(p, q)) return; // Rename p’s component to q’s name. for (int i = 0; i < id.length; i++) if (id[i] == id[p]) id[i] = id[q]; count--; }
1.5.8 In the loop, id[p] will eventually be set to id[q], losing the reference to the original parent. This will make the next elements with id[i] == id[p] to not have their values updated. Counterexample: id[p] = 2 id[q] = 4 Array 0 1 2 2 4 2 6 0 != 2, is not updated 1 != 2, is not updated 2 == 2, is updated to 4...
[]
{ "number": "1.5.8", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false }
In the weighted quick-union algorithm, suppose that we set id[find(p)] to q instead of to id[find(q)]. Would the resulting algorithm be correct?
1.5.10 Yes, but that would increase the maximum possible height of the trees to N, which would decrease find()'s worst case performance from lg (N) to N and, consequently, decrease union()'s worst case performance to N.
[]
{ "number": "1.5.10", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Exercise", "code_execution": false }
Quick-union with path compression. Modify quick-union (page 224) to include path compression, by adding a loop to union() that links every site on the paths from p and q to the roots of their trees to the root of the new tree. Give a sequence of input pairs that causes this method to produce a path of length 4. Note: T...
public void union(int p, int q) { int pRoot = root(p); int qRoot = root(q); if (pRoot == qRoot) { return; } id[pRoot] = qRoot; while (p != qRoot) { int next = id[p]; id[p] = qRoot; p = next; } while (q != qRoot) { int next = id[q]; id[q] ...
[]
{ "number": "1.5.12", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false }
Amortized costs plots. Instrument your implementations from Exercise 1.5.7 to make amortized costs plots like those in the text.
// Exercise16_AmortizedCostsPlotsQF.java package chapter1.section5; import util.GraphPanel; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import javax.swing.*; import java.util.ArrayList; import java.util.List; /** * Created by Rene Argento on 08/12/16. */ public class Exercise16_A...
[]
{ "number": "1.5.16", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false }
Random connections. Develop a UF client ErdosRenyi that takes an integer value N from the command line, generates random pairs of integers between 0 and N-1, calling connected() to determine if they are connected and then union() if not (as in our development client), looping until all sites are connected, and printing...
```java import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.WeightedQuickUnionUF; public class ErdosRenyi { public static int count(int n) { WeightedQuickUnionUF uf = new WeightedQuickUnionUF(n); int connections = 0; while (uf.count()...
[]
{ "number": "1.5.17", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false }
Random grid generator. Write a program RandomGrid that takes an int value N from the command line, generates all the connections in an N-by-N grid, puts them in random order, randomly orients them (so that p q and q p are equally likely to occur), and prints the result to standard output. To randomly order the connecti...
package chapter1.section5; import chapter1.section3.Exercise34_RandomBag; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; public class RandomGrid { public static class Connection { int p; int q; Connection(int p, int q) { this.p = p; t...
[]
{ "number": "1.5.18", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false }
Animation. Write a RandomGrid client (see Exercise 1.5.18) that uses UnionFind as in our development client to check connectivity and uses StdDraw to draw the connections as they are processed.
Use `RandomGrid.generate(N)` to produce all grid connections in random order, draw each connection as it is processed, and stop when the union-find structure reports one component. ```java public static void main(String[] args) { int n = Integer.parseInt(args[0]); int sites = n * n; WeightedQuickUnionUF uf...
[]
{ "number": "1.5.19", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Creative Problem", "code_execution": false }
Doubling test for random grids. Develop a performance-testing client that takes an int value T from the command line and performs T trials of the following experiment: Use your client from Exercise 1.5.18 to generate the connections in an N-by-N square grid, randomly oriented and in random order, then use UnionFind to ...
For each grid size `N`, run exactly `T` independent trials, average the number of connections processed and the elapsed time, then double `N`. ```java for (int n = 8; true; n += n) { Stopwatch timer = new Stopwatch(); long totalConnections = 0; for (int t = 0; t < T; t++) { WeightedQuickUnionUF uf ...
[]
{ "number": "1.5.25", "chapter": 1, "chapter_title": "Fundamentals", "section": 1.5, "section_title": "Case Study: Union-Find", "type": "Experiment", "code_execution": false }
Show, in the style of the example trace with Algorithm 2.1, how selection sort sorts the array E A S Y Q U E S T I O N.
2.1.1 a[] i min 0 1 2 3 4 5 6 7 8 9 10 11 E A S Y Q U E S T I O N 0 1 E A S Y Q U E S T I O N 1 1 A E S Y Q U E S T I O N 2 6 A E S Y Q U E S T I O N 3 9 A E E Y Q U S S T I O N 4 11 A E E I Q U S S T Y O N 5 10 A E E I N U S S T Y O Q 6 11 A E E I N O S S T Y U Q 7 7 ...
[]
{ "number": "2.1.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
What is the maximum number of exchanges involving any particular element during selection sort? What is the average number of exchanges involving an element?
2.1.2 The maximum number of exchanges involving any particular item during selection sort is N - 1. This happens when the first item has the highest value in the unsorted array and the other values are sorted. For example, in the array 4 1 2 3, the element 4 will be swapped N - 1 times. The average number of exchanges ...
[]
{ "number": "2.1.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Give an example of an array of N items that maximizes the number of times the test a[j] < a[min] succeeds (and, therefore, min gets updated) during the operation of selection sort (Algorithm 2.1).
2.1.3 Array: H G F E D C B A Thanks to QiotoF (https://github.com/QiotoF) for mentioning a better array solution for this exercise https://github.com/reneargento/algorithms-sedgewick-wayne/issues/76
[]
{ "number": "2.1.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Show, in the style of the example trace with Algorithm 2.2, how insertion sort sorts the array E A S Y Q U E S T I O N.
2.1.4 a[] i j 0 1 2 3 4 5 6 7 8 9 10 11 E A S Y Q U E S T I O N 0 0 E A S Y Q U E S T I O N 1 0 A E S Y Q U E S T I O N 2 2 A E S Y Q U E S T I O N 3 3 A E S Y Q U E S T I O N 4 2 A E Q S Y U E S T I O N 5 4 A E Q S U Y E S T I O N 6 2 A E E Q S U Y S T I O N 7 5 ...
[]
{ "number": "2.1.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
For each of the two conditions in the inner for loop in insertion sort (Algorithm 2.2), describe an array of N items where that condition is always false when the loop terminates.
2.1.5 Condition 1: j > 0 -> When the array is reverse ordered Z Q K D C B A Condition 2: less(a[j], a[j - 1]) -> When the array is ordered A B C D E F G
[]
{ "number": "2.1.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Which method runs faster for an array with all keys identical, selection sort or insertion sort?
2.1.6 Insertion sort because it will only make one comparison with the previous element (per element) and won't exchange any elements, running in linear time. Selection sort will exchange each element with itself and will run in quadratic time. Thanks to glucu (https://github.com/glucu) for correcting the number of e...
[]
{ "number": "2.1.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Which method runs faster for an array in reverse order, selection sort or insertion sort?
2.1.7 Selection sort because even though both selection sort and insertion sort will run in quadratic time, selection sort will only make N exchanges, while insertion sort will make N * N / 2 exchanges. Thanks to LudekCizinsky (https://github.com/LudekCizinsky), rg9a27 (https://github.com/rg9a27) and BOTbkcd (https:/...
[]
{ "number": "2.1.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Suppose that we use insertion sort on a randomly ordered array where elements have only one of three values. Is the running time linear, quadratic, or something in between?
2.1.8 Quadratic. Insertion sort's running time is linear when the array is already sorted or all elements are equal. With three possible values the running time quadratic.
[]
{ "number": "2.1.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Show, in the style of the example trace with Algorithm 2.3, how shellsort sorts the array E A S Y S H E L L S O R T Q U E S T I O N.
2.1.9 a[] h i j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 E A S Y S H E L L S O R T Q U E S T I O N 13 13 13 E A S Y S H E L L S O R T Q U E S T I O N 13 14 14 E A S Y S H E L L S O R T Q U E S T I O N 13 15 2 E A E Y S H E L L S O R T Q U S S ...
[]
{ "number": "2.1.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Why not use selection sort for h-sorting in shellsort?
2.1.10 Insertion sort is faster than selection sort for h-sorting because as "h" decreases, the array becomes partially sorted. Insertion sort makes less comparisons in partially sorted arrays than selection sort. Also, when h-sorting, eventually h will have an increment value of 1. Using selection sort with an increme...
[]
{ "number": "2.1.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Exercise", "code_execution": false }
Deck sort. Explain how you would put a deck of cards in order by suit (in the order spades, hearts, clubs, diamonds) and by rank within each suit, with the restriction that the cards must be laid out face down in a row, and the only allowed operations are to check the values of two cards and to exchange two cards (keep...
2.1.13 - Deck sort I would use selection sort, comparing the cards first by suit, and if they have the same suit, by rank. As we are dealing with physical objects it makes sense to minimize the number of swaps. With selection sort it may be needed to look at more cards than insertion sort (twice as many in the average ...
[]
{ "number": "2.1.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false }
Dequeue sort. Explain how you would sort a deck of cards, with the restriction that the only allowed operations are to look at the values of the top two cards, to exchange the top two cards, and to move the top card to the bottom of the deck.
2.1.14 - Dequeue sort I would use a variation of bubble sort. 1- I would compare both top cards and, if the top card were bigger than the second card, I would swap them. 2- I would mark the top card, so I could know it was the first card (in this iteration) sent to the bottom of the deck. 3- I would send the top card ...
[]
{ "number": "2.1.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false }
Expensive exchange. A clerk at a shipping company is charged with the task of rearranging a number of large crates in order of the time they are to be shipped out. Thus, the cost of compares is very low (just look at the labels) relative to the cost of exchanges (move the crates). The warehouse is nearly full—there is ...
2.1.15 - Expensive exchange The clerk should use selection sort. Since the cost of compares is low, the N^2 complexity won't be a problem. And it guarantees a cost of at most N exchanges.
[]
{ "number": "2.1.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false }
Shellsort best case. What is the best case for shellsort? Justify your answer.
2.1.20 - Shellsort best case Just like insertion sort, the best case for shellsort is when the array is already ordered. This causes every element to be compared only once in each iteration. The time complexity in this case is O(n log n). Good explanation: https://www.toptal.com/developers/sorting-algorithms/shell-...
[]
{ "number": "2.1.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.1, "section_title": "Elementary Sorts", "type": "Creative Problem", "code_execution": false }
Give a trace, in the style of the trace given at the beginning of this section, showing how the keys A E Q S U Y E I N O S T are merged with the abstract in-place merge() method.
2.2.1 a[] aux[] k 0 1 2 3 4 5 6 7 8 9 10 11 i j 0 1 2 3 4 5 6 7 8 9 10 11 input A E Q S U Y E I N O S T - - - - - - - - - - - - copy A E Q S U Y E I N O...
[]
{ "number": "2.2.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Give traces, in the style of the trace given with Algorithm 2.4, showing how the keys E A S Y Q U E S T I O N are sorted with top-down mergesort.
2.2.2 a[] 0 1 2 3 4 5 6 7 8 9 10 11 E A S Y Q U E S T I O N merge(a, 0, 0, 1) A E S Y Q U E S T I O N merge(a, 0, 1, 2) A E S Y Q U E S T I O N merge...
[]
{ "number": "2.2.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Answer Exercise 2.2.2 for bottom-up mergesort.
2.2.3 a[] 0 1 2 3 4 5 6 7 8 9 10 11 sz = 1 E A S Y Q U E S T I O N merge(a, 0, 0, 1) A E S Y Q U E S T I O N merge(a, 2, 2, 3) A E S Y Q U E S T I O N...
[]
{ "number": "2.2.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Does the abstract in-place merge produce proper output if and only if the two input subarrays are in sorted order? Prove your answer, or provide a counterexample.
2.2.4 Yes. The merge phase uses two pointers that move comparing both subarray values. Once it finds that one value is smaller than the other, it selects this value for the output without checking the other elements. If one or more of the input subarrays are not sorted then some values would be considered in the wrong...
[]
{ "number": "2.2.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Give the sequence of subarray sizes in the merges performed by both the top-down and the bottom-up mergesort algorithms, for N = 39.
2.2.5 Top-down mergesort: 2, 3, 2, 5, 2, 3, 2, 5, 10, 2, 3, 2, 5, 2, 3, 2, 5, 10, 20, 2, 3, 2, 5, 2, 3, 2, 5, 10, 2, 3, 2, 5, 2, 2, 4, 9, 19, 39. Bottom-up mergesort: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 8, 8, 8, 8, 7, 16, 16, 32, 39.
[]
{ "number": "2.2.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Write a program to compute the exact value of the number of array accesses used by top-down mergesort and by bottom-up mergesort. Use your program to plot the values for N from 1 to 512, and to compare the exact values with the upper bound 6N lg N.
// Exercise6.java package chapter2.section2; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import java.util.HashMap; import java.util.Map; /** * Created by Rene Argento on 11/02/17. */ // Thanks to ajfg93 (https://github.com/ajfg93) for correcting the array access count. // https:/...
[]
{ "number": "2.2.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Show that the number of compares used by mergesort is monotonically increasing (C(N+1) > C(N) for all N > 0).
For top-down mergesort in the worst case, the number of compares C(N) satisfies C(1) = 0 C(N) = C(floor(N/2)) + C(ceil(N/2)) + N - 1 The merge of two sorted subarrays whose total length is N uses at most N - 1 compares. To prove C(N + 1) > C(N), compare the recurrences. Increasing the input size by one increases one ...
[]
{ "number": "2.2.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Suppose that Algorithm 2.4 is modified to skip the call on merge() whenever a[mid] <= a[mid+1]. Prove that the number of compares used to mergesort a sorted array is linear.
2.2.8 Since the array is already sorted, merge() will always be skipped. So there won't be any values copied from the aux array to the original array (only values copied from the original array to the aux array). Therefore, there will be only 1 compare for every subarray, which is a linear operation. When N is a powe...
[]
{ "number": "2.2.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Use of a static array like aux[] is inadvisable in library software because multiple clients might use the class concurrently. Give an implementation of Merge that does not use a static array. Do not make aux[] local to merge() (see the Q&A for this section). Hint: Pass the auxiliary array as an argument to the recursi...
package chapter2.section2; import edu.princeton.cs.algs4.StdRandom; /** * Created by Rene Argento on 11/02/17. */ public class Exercise9 { public static void main(String[] args) { Comparable[] array = generateRandomArray(1000); topDownMergeSort(array); } private static Comparable[] ge...
[]
{ "number": "2.2.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Exercise", "code_execution": false }
Faster merge. Implement a version of merge() that copies the second half of a[] to aux[] in decreasing order and then does the merge back to a[]. This change allows you to remove the code to test that each of the halves has been exhausted from the inner loop. Note: The resulting sort is not stable (see page 341).
package chapter2.section2; import util.ArrayGenerator; /** * Created by Rene Argento on 12/02/17. */ @SuppressWarnings("rawtypes") public class Exercise10_FasterMerge { public static void main(String[] args) { Comparable[] array = ArrayGenerator.generateRandomArray(1000); topDownMergeSort(array...
[]
{ "number": "2.2.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false }
Lower bound for average case. Prove that the expected number of compares used by any compare-based sorting algorithm must be at least ~N lg N (assuming that all possible orderings of the input are equally likely). Hint: The expected number of compares is at least the external path length of the compare tree (the sum of...
2.2.13 - Lower bound for average case Based on: https://www.cs.cmu.edu/~avrim/451f11/lectures/lect0913.pdf Theorem: For any deterministic comparison-based sorting algorithm A, the average-case number of comparisons (the number of comparisons on average on a randomly chosen permutation of n distinct elements) is at le...
[]
{ "number": "2.2.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false }
Merging sorted queues. Develop a static method that takes two queues of sorted items as arguments and returns a queue that results from merging the queues into sorted order.
package chapter2.section2; import edu.princeton.cs.algs4.Queue; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 13/02/17. */ // Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for suggesting a simpler method to merge the queues: // https://github.com/reneargento/algorithms-sedgew...
[]
{ "number": "2.2.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false }
Bottom-up queue mergesort. Develop a bottom-up mergesort implementation based on the following approach: Given N items, create N queues, each containing one of the items. Create a queue of the N queues. Then repeatedly apply the merging operation of Exercise 2.2.14 to the first two queues and reinsert the merged queue ...
package chapter2.section2; import edu.princeton.cs.algs4.Queue; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; /** * Created by Rene Argento on 13/02/17. */ public class Exercise15_BottomUpQueueMergesort { public static void main(String[] args) { Comparable[] array = ge...
[]
{ "number": "2.2.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false }
Indirect sort. Develop and implement a version of mergesort that does not rearrange the array, but returns an int[] array perm such that perm[i] is the index of the ith smallest entry in the array.
package chapter2.section2; import edu.princeton.cs.algs4.StdOut; /** * Created by Rene Argento on 18/02/17. */ //Based on http://algs4.cs.princeton.edu/22mergesort/Merge.java.html public class Exercise20_IndexSort { public static void main(String[] args) { Comparable[] array1 = generateArray1(); ...
[]
{ "number": "2.2.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.2, "section_title": "Mergesort", "type": "Creative Problem", "code_execution": false }
Show, in the style of the trace given with partition(), how that method partitions the array E A S Y Q U E S T I O N.
2.3.1 a[] i j 0 1 2 3 4 5 6 7 8 9 10 11 initial values 0 12 E A S Y Q U E S T I O N scan left, scan right 2 6 E A S Y Q U E S T I O N exchange 2 6 E A E Y Q U S S...
[]
{ "number": "2.3.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Show, in the style of the quicksort trace given in this section, how quicksort sorts the array E A S Y Q U E S T I O N (for the purposes of this exercise, ignore the initial shuffle).
2.3.2 a[] lo j hi 0 1 2 3 4 5 6 7 8 9 10 11 E A S Y Q U E S T I O N 0 2 11 E A E Y Q U S S T I O N 0 1 1 A E E Y Q U S S T I O N 0 0 A E E Y Q U S S T I O N 3 11 11 A E E...
[]
{ "number": "2.3.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
What is the maximum number of times during the execution of Quick.sort() that the largest item can be exchanged, for an array of length N?
2.3.3 The maximum number of times during the execution of Quick.sort() that the largest item can be exchanged, for an array of length N is floor(N / 2). Note that this answer is specific to this version of quicksort in which the first element is always selected as the pivot. Reference: https://stackoverflow.com/quest...
[]
{ "number": "2.3.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Suppose that the initial random shuffle is omitted. Give six arrays of ten elements for which Quick.sort() uses the worst-case number of compares.
2.3.4 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [11, 10, 9, 8, 7, 6, 5, 4, 3, 2] [12, 11, 10, 9, 8, 7, 6, 5, 4, 3]
[]
{ "number": "2.3.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Give a code fragment that sorts an array that is known to consist of items having just two distinct keys.
package chapter2.section3; import edu.princeton.cs.algs4.StdOut; import util.ArrayGenerator; import java.util.StringJoiner; /** * Created by Rene Argento on 04/03/17. */ public class Exercise5 { public static void main(String[] args) { int arrayLength = Integer.parseInt(args[0]); Comparable ar...
[]
{ "number": "2.3.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Write a program to compute the exact value of CN, and compare the exact value with the approximation 2N ln N, for N = 100, 1,000, and 10,000.
For standard quicksort with random distinct keys, `C_0 = C_1 = 0` and, for `N >= 2`, `C_N = N + 1 + (2 / N) * (C_0 + C_1 + ... + C_{N-1})`. Equivalently, `C_N = 2(N + 1)H_N - 4N`. | N | exact C_N | 2N ln N | |---:|---:|---:| | 100 | 648 | 921 | | 1,000 | 10,986 | 13,816 | | 10,000 | 155,772 | 184,207 | The previo...
[]
{ "number": "2.3.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Find the expected number of subarrays of size 0, 1, and 2 when quicksort is used to sort an array of N items with distinct keys. If you are mathematically inclined, do the math; if not, run some experiments to develop hypotheses.
2.3.7 Array Size | SubArrays Size 0 | SubArrays Size 1 | SubArrays Size 2 1000 325 338 174 2000 657 672 333 4000 1383 1309 681 8000 ...
[]
{ "number": "2.3.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
About how many compares will Quick.sort() make when sorting an array of N items that are all equal?
2.3.8 When sorting an array of N items that are all equal, Quick.sort() will make approximately N lg N compares. Each partition will divide the array in half, plus or minus one.
[]
{ "number": "2.3.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Explain what happens when Quick.sort() is run on an array having items with just two distinct keys, and then explain what happens when it is run on an array having just three distinct keys.
2.3.9 On both cases (when Quick.sort() is run on arrays having items with just two or three distinct keys) there is a high occurrence of subarrays consisting solely of items with equal keys. To improve performance when sorting such arrays (from linearithmic to linear) quicksort with 3-way partitioning should be used.
[]
{ "number": "2.3.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Chebyshev’s inequality says that the probability that a random variable is more than k standard deviations away from the mean is less than 1/k^2. For N = 1 million, use Chebyshev’s inequality to bound the probability that the number of compares used by quicksort is more than 100 billion (.1 N^2).
2.3.10 There are 1 million elements, so N = 1,000,000. As mentioned on the book, quicksort uses ~2N ln N compares on the average case to sort N keys. Therefore, on average there will be 27,620,000 compares. As also mentioned on the book, the standard deviation of the number of compares is about .65 N, which in this c...
[]
{ "number": "2.3.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
What is the recursive depth of quicksort, in the best, worst, and average cases? This is the size of the stack that the system needs to keep track of the recursive calls. See Exercise 2.3.20 for a way to guarantee that the recursive depth is logarithmic in the worst case.
2.3.13 Recursive depth in the best case: logarithmic Recursive depth in the worst case: linear Recursive depth in the average case: logarithmic (if the pivot is chosen at random or if the array is shuffled before the sort begins).
[]
{ "number": "2.3.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Prove that when running quicksort on an array with N distinct items, the probability of comparing the ith and jth largest items is 2/(j - i + 1). Then use this result to prove Proposition K.
2.3.14 The ith and jth elements will be compared if either of them is selected as pivot. In an array of size (j - i + 1), the probability of choosing either the ith or the jth element as the pivot is 2 / (j - i + 1). Therefore, when running quicksort on an array with N distinct items, the probability of comparing th...
[]
{ "number": "2.3.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Exercise", "code_execution": false }
Nuts and bolts. (G. J. E. Rawlins) You have a mixed pile of N nuts and N bolts and need to quickly find the corresponding pairs of nuts and bolts. Each nut matches exactly one bolt, and each bolt matches exactly one nut. By fitting a nut and bolt together, you can see which is bigger, but it is not possible to directly...
2.3.15 - Nuts and bolts Since each nut matches exactly one bolt, the array of nuts and the array of bolts have distinct elements. To avoid a O(N^2) complexity, initially I would shuffle the nuts array. I would then use Quicksort's partition method: 1- Select a nut as the pivot (since the array is shuffled it is safe ...
[]
{ "number": "2.3.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false }
Nonrecursive quicksort. Implement a nonrecursive version of quicksort based on a main loop where a subarray is popped from a stack to be partitioned, and the resulting subarrays are pushed onto the stack. Note: Push the larger of the subarrays onto the stack first, which guarantees that the stack will have at most lg N...
// Exercise20_NonrecursiveQuicksort.java package chapter2.section3; import edu.princeton.cs.algs4.Stack; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.Stopwatch; import util.ArrayUtil; import util.ArrayGenerator; import java.util.Map; /** * Created by R...
[]
{ "number": "2.3.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false }
Java system sort. Add to your implementation from Exercise 2.3.22 code to use the Tukey ninther to compute the partitioning item—choose three sets of three items, take the median of each, then use the median of the three medians as the partitioning item. Also, add a cutoff to insertion sort for small subarrays.
// Exercise23_TukeysNinther.java package chapter2.section3; import chapter2.section1.InsertionSort; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.Stopwatch; import util.ArrayUtil; import util.ArrayGenerator; import java.util.HashMap; import java.util.Map;...
[]
{ "number": "2.3.23", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false }
Samplesort. (W. Frazer and A. McKellar) Implement a quicksort based on using a sample of size 2k - 1. First, sort the sample, then arrange to have the recursive routine partition on the median of the sample and to move the two halves of the rest of the sample to each subarray, such that they can be used in the subarray...
// Exercise24_Samplesort.java package chapter2.section3; import chapter2.section1.InsertionSort; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.Stopwatch; import util.ArrayUtil; import util.ArrayGenerator; import java.util.Map; /** * Created by Rene Arge...
[]
{ "number": "2.3.24", "chapter": 2, "chapter_title": "Sorting", "section": 2.3, "section_title": "Quicksort", "type": "Creative Problem", "code_execution": false }
Suppose that the sequence P R I O * R * * I * T * Y * * * Q U E * * * U * E (where a letter means insert and an asterisk means remove the maximum) is applied to an initially empty priority queue. Give the sequence of letters returned by the remove the maximum operations.
2.4.1 R R P O T Y I I U Q E U (E is left on the priority queue)
[]
{ "number": "2.4.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Criticize the following idea: To implement find the maximum in constant time, why not use a stack or a queue, but keep track of the maximum value inserted so far, then return that value for find the maximum?
2.4.2 This idea would not work because it only keeps track of the current maximum. After a remove-the-maximum operation it would not be possible to know which is the next maximum in constant time, requiring a linear operation to find the new maximum.
[]
{ "number": "2.4.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Provide priority-queue implementations that support insert and remove the maximum, one for each of the following underlying data structures: unordered array, ordered array, unordered linked list, and linked list. Give a table of the worst-case bounds for each operation for each of your four implementations.
2.4.3 Data Structure Method Worst-case Unordered array Insert 1 Unordered array Remove the Maximum N Ordered array Insert N Ordered array Remove the Maximum 1 Unordered linked list Insert 1 Unordered...
[]
{ "number": "2.4.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Is an array that is sorted in decreasing order a max-oriented heap?
2.4.4 Yes, an array that is sorted in decreasing order is a max-oriented heap.
[]
{ "number": "2.4.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Give the heap that results when the keys E A S Y Q U E S T I O N are inserted in that order into an initially empty max-oriented heap.
2.4.5 1- E 2- E A 3- S A E 4- Y S E A 5- Y S E A Q 6- Y S U A Q E 7- Y S U A Q E E 8- Y S U S Q E E A 9- Y T U S Q E E A S 10- Y T U S Q E E A S I 11- Y T U S Q E E A S I O 12- Y T U S Q N E ...
[]
{ "number": "2.4.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Using the conventions of Exercise 2.4.1, give the sequence of heaps produced when the operations P R I O * R * * I * T * Y * * * Q U E * * * U * E are performed on an initially empty max-oriented heap.
2.4.6 Heaps: 1- P 2- R P 3- R P I 4- R P I O 5- P O I 6- R P I O 7- P O I 8- O I 9- O I I 10- I I 11- T I I 12- I I 13- Y I I 14- I I 15- I 16- 17- Q 18- U Q 19- U Q E 20- Q E 21- E 22- 23- U 24- 25- E
[]
{ "number": "2.4.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
The largest item in a heap must appear in position 1, and the second largest must be in position 2 or position 3. Give the list of positions in a heap of size 31 where the kth largest (i) can appear, and (ii) cannot appear, for k=2, 3, 4 (assuming the values to be distinct).
2.4.7 Heap-of-size-31 positions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Kth largest item Can appear Cannot appear 2 ...
[]
{ "number": "2.4.7", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Answer the previous exercise for the kth smallest item.
2.4.8 Kth smallest item Can appear Cannot appear 2 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 3 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27...
[]
{ "number": "2.4.8", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Draw all of the different heaps that can be made from the five keys A B C D E, then draw all of the different heaps that can be made from the five keys A A A B B.
2.4.9 Using A,B,C,D,E keys 1- E D C B A 2- E D C A B 3- E C D B A 4- E C D A B 5- E D A C B 6- E D A B C 7- E D B C A 8- E D B A C Using A,A,A,B,B keys 1- B B A A A 2- B A B A A
[]
{ "number": "2.4.9", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Suppose that we wish to avoid wasting one position in a heap-ordered array pq[], putting the largest value in pq[0], its children in pq[1] and pq[2], and so forth, proceeding in level order. Where are the parents and children of pq[k]?
2.4.10 Parent of pq[k]: pq[(k - 1) / 2] (Rounded down) Children of pq[k]: Left: pq[k * 2 + 1] Right: pq[k * 2 + 2]
[]
{ "number": "2.4.10", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Describe a way to avoid the j < N test in sink().
2.4.13 Changing the line: while (2*k <= N) To: while (2*k < N) Would guarantee that all indices (2*k + 1) are <= N and with that, the j < N verification would not be necessary. However, an additional verification would be necessary for the last level of the heap if the node being compared in level n-1 only has a l...
[]
{ "number": "2.4.13", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
What is the minimum number of items that must be exchanged during a remove the maximum operation in a heap of size N with no duplicate keys? Give a heap of size 15 for which the minimum is achieved. Answer the same questions for two and three successive remove the maximum operations.
2.4.14 The minimum number of items that must be exchanged during a remove the maximum operation in a heap of size N with no duplicate keys is 2. Heap: 100 99 98 9 10 97 96 5 6 7 8 95 94 93 92 For two successive remove the maximum ope...
[]
{ "number": "2.4.14", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.
public static boolean isMinHeap(Comparable[] pq, int n) { for (int k = 1; k <= n / 2; k++) { if (2 * k <= n && greater(pq[k], pq[2 * k])) { return false; } if (2 * k + 1 <= n && greater(pq[k], pq[2 * k + 1])) { return false; } } return true; } private...
[]
{ "number": "2.4.15", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Prove that sink-based heap construction uses fewer than 2N compares and fewer than N exchanges.
2.4.20 Sink-based heap construction uses fewer than 2N compares and fewer than N exchanges. Proof: It suffices to prove that sink-based heap construction uses fewer than n exchanges because the number of compares is at most twice the number of exchanges. For simplicity, assume that the binary heap is perfect (i.e., a...
[]
{ "number": "2.4.20", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Exercise", "code_execution": false }
Multiway heaps. Considering the cost of compares only, and assuming that it takes t compares to find the largest of t items, find the value of t that minimizes the coefficient of N lg N in the compare count when a t-ary heap is used in heapsort. First, assume a straightforward generalization of sink(); then, assume tha...
In a t-ary heap, the height is log_t N = lg N / lg t. In the straightforward sink(), each level needs t - 1 compares to find the largest child and one more compare to decide whether to exchange with that child, for about t compares per level. The leading coefficient of N lg N is therefore proportional to t / lg t ...
[]
{ "number": "2.4.23", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Priority queue with explicit links. Implement a priority queue using a heap-ordered binary tree, but use a triply linked structure instead of an array. You will need three links per node: two to traverse down the tree and one to traverse up the tree. Your implementation should guarantee logarithmic running time per ope...
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import util.ArrayUtil; /** * Created by Rene Argento on 23/03/17. */ @SuppressWarnings("unchecked") public class Exercise24_PriorityQueueExplicitLinks<Key extends Comparable> { private class PQNode { PQNode parent; PQNode leftChil...
[]
{ "number": "2.4.24", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Computational number theory. Write a program CubeSum.java that prints out all integers of the form a^3 + b^3 where a and b are integers between 0 and N in sorted order, without using excessive space. That is, instead of computing an array of the N^2 sums and sorting them, build a minimum-oriented priority queue, initia...
Maintain one pending item for each possible `a`, where the item stores `(sum, a, b)` and `sum = a^3 + b^3`. Delete the minimum sum, print it, and then insert the next value for the same `a`. ```java import edu.princeton.cs.algs4.MinPQ; import edu.princeton.cs.algs4.StdOut; public class CubeSum implements Comparable<C...
[]
{ "number": "2.4.25", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Heap without exchanges. Because the exch() primitive is used in the sink() and swim() operations, the items are loaded and stored twice as often as necessary. Give more efficient implementations that avoid this inefficiency, a la insertion sort (see Exercise 2.1.25).
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import util.ArrayUtil; /** * Created by Rene Argento on 25/03/17. */ @SuppressWarnings("unchecked") public class Exercise26_HeapWithoutExchanges { private enum Orientation { MAX, MIN; } private class PriorityQueue<Key extends Com...
[]
{ "number": "2.4.26", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Find the minimum. Add a min() method to MaxPQ. Your implementation should use constant time and constant extra space.
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import util.ArrayUtil; /** * Created by Rene Argento on 25/03/17. */ @SuppressWarnings("unchecked") public class Exercise27_FindTheMinimum { private class PriorityQueue<Key extends Comparable<Key>> { private Key[] priorityQueue; ...
[]
{ "number": "2.4.27", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Selection filter. Write a TopM client that reads points (x, y, z) from standard input, takes a value M from the command line, and prints the M points that are closest to the origin in Euclidean distance. Estimate the running time of your client for N = 10^8 and M = 10^4.
// Exercise28_SelectionFilter.java package chapter2.section4; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.Stopwatch; import java.util.Stack; /** * Created by Rene Argento on 25/03/17. */ public class Exercise28_Se...
[]
{ "number": "2.4.28", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Min/max priority queue. Design a data type that supports the following operations: insert, delete the maximum, and delete the minimum (all in logarithmic time); and find the maximum and find the minimum (both in constant time). Hint: Use two heaps.
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import util.ArrayUtil; /** * Created by Rene Argento on 25/03/17. */ // Based on: http://eranle.blogspot.com.br/2012/08/min-max-heap-java-implementation.html // Thanks to YRFT (https://github.com/YRFT) for finding that the method deleteItem() also nee...
[]
{ "number": "2.4.29", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Dynamic median-finding. Design a data type that supports insert in logarithmic time, find the median in constant time, and delete the median in logarithmic time. Hint: Use a min-heap and a max-heap.
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import util.ArrayUtil; /** * Created by Rene Argento on 26/03/17. */ public class Exercise30_DynamicMedianFinding { private class DynamicMedianFindingHeap<Key extends Comparable<Key>> { private PriorityQueueResize<Key> minPriorityQueue; ...
[]
{ "number": "2.4.30", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Fast insert. Develop a compare-based implementation of the MinPQ API such that insert uses ~log log N compares and delete the minimum uses ~2 log N compares. Hint: Use binary search on parent pointers to find the ancestor in swim().
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import util.ArrayUtil; /** * Created by Rene Argento on 26/03/17. */ // Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for suggesting an improved binarySearchToGetTargetAncestor() method. // https://github.com/reneargento/algorithms-sedg...
[]
{ "number": "2.4.31", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Index priority-queue implementation (additional operations). Add minIndex(), change(), and delete() to your implementation of Exercise 2.4.33.
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import java.util.NoSuchElementException; /** * Created by Rene Argento on 26/03/17. */ //Based on http://algs4.cs.princeton.edu/24pq/IndexMaxPQ.java.html @SuppressWarnings("unchecked") public class Exercise34_...
[]
{ "number": "2.4.34", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Sampling from a discrete probability distribution. Write a class Sample with a constructor that takes an array p[] of double values as argument and supports the following two operations: random()—return an index i with probability p[i]/T (where T is the sum of the numbers in p[])—and change(i, v)—change the value of p[...
package chapter2.section4; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import java.util.HashMap; import java.util.Map; /** * Created by Rene Argento on 27/03/17. */ // Thanks to dragon-dreamer (https://github.com/dragon-dreamer) for fixing the random() method. // https://github.c...
[]
{ "number": "2.4.35", "chapter": 2, "chapter_title": "Sorting", "section": 2.4, "section_title": "Priority Queues", "type": "Creative Problem", "code_execution": false }
Consider the following implementation of the compareTo() method for String. How does the third line help with efficiency? public int compareTo(String that) { if (this == that) return 0; // this line int n = Math.min(this.length(), that.length()); for (int i = 0; i < n; i++) { if (this.charAt(i) < that.charAt(i)) ...
2.5.1 The third line helps with efficiency by checking if the two objects being compared are the same (when both references point to the same object). This verification helps to avoid iterating through all characters on both Strings in the case that both objects are the same.
[]
{ "number": "2.5.1", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false }
Write a program that reads a list of words from standard input and prints all two-word compound words in the list. For example, if after, thought, and afterthought are in the list, then afterthought is a compound word.
package chapter2.section5; import edu.princeton.cs.algs4.StdOut; import java.util.*; /** * Created by Rene Argento on 09/04/17. */ // Thanks to Vivek Bhojawala (https://github.com/VBhojawala) for suggesting a simpler code to solve this exercise. // https://github.com/reneargento/algorithms-sedgewick-wayne/issues/1...
[]
{ "number": "2.5.2", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false }
Criticize the following implementation of a class intended to represent account balances. Why is compareTo() a flawed implementation of the Comparable interface? public class Balance implements Comparable<Balance> { ... private double amount; public int compareTo(Balance that) { if (this.amount < that.amount - 0....
2.5.3 The compareTo() is a flawed implementation of the Comparable interface because it violates the Comparable contract. The contract says that if x.compareTo(y) == 0 then the sign of x.compareTo(z) must be equal to the sign of y.compareTo(z), for all z. In the implementation described in the exercise, if x = 0.001, ...
[]
{ "number": "2.5.3", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false }
Implement a method String[] dedup(String[] a) that returns the objects in a[] in sorted order, with duplicates removed.
package chapter2.section5; import edu.princeton.cs.algs4.StdOut; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Rene Argento on 09/04/17. */ public class Exercise4 { public static void main(String[] args) { String[] input = {"Algorithms", "Sedgewick", "Way...
[]
{ "number": "2.5.4", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false }
Explain why selection sort is not stable.
2.5.5 Selection sort is not stable because it exchanges nonadjacent elements. On the example below, the first B gets swapped to the right of the second B. i min 0 1 2 0 2 B1 B2 A 1 1 A B2 B1 2 2 A B2 B1 A B2 B1
[]
{ "number": "2.5.5", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false }
Implement a recursive version of select().
package chapter2.section5; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import util.ArrayUtil; /** * Created by Rene Argento on 09/04/17. */ // Thanks to ckwastra (https://github.com/ckwastra) for reporting a bug in recursiveSelect(). // https://github.com/reneargento/algorithms-se...
[]
{ "number": "2.5.6", "chapter": 2, "chapter_title": "Sorting", "section": 2.5, "section_title": "Applications", "type": "Exercise", "code_execution": false }