question
stringlengths 34
5.67k
| answer
stringlengths 20
20.1k
| support_files
listlengths 0
4
| metadata
dict |
|---|---|---|---|
Add a method isFull() to /******************************************************************************
* Compilation: javac FixedCapacityStackOfStrings.java
* Execution: java FixedCapacityStackOfStrings
* Dependencies: StdIn.java StdOut.java
*
* Stack of strings implementation with a fixed-size array.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java FixedCapacityStackOfStrings 5 < tobe.txt
* to be not that or be
*
* Remark: bare-bones implementation. Does not do repeated
* doubling or null out empty array entries to avoid loitering.
*
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class FixedCapacityStackOfStrings implements Iterable<String> {
private String[] a; // holds the items
private int n; // number of items in stack
// create an empty stack with given capacity
public FixedCapacityStackOfStrings(int capacity) {
a = new String[capacity];
n = 0;
}
public boolean isEmpty() {
return n == 0;
}
public boolean isFull() {
return n == a.length;
}
public void push(String item) {
a[n++] = item;
}
public String pop() {
return a[--n];
}
public String peek() {
return a[n-1];
}
public Iterator<String> iterator() {
return new ReverseArrayIterator();
}
// an array iterator, in reverse order
public class ReverseArrayIterator implements Iterator<String> {
private int i = n-1;
public boolean hasNext() {
return i >= 0;
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i--];
}
}
public static void main(String[] args) {
int max = Integer.parseInt(args[0]);
FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) stack.push(item);
else if (stack.isEmpty()) StdOut.println("BAD INPUT");
else StdOut.print(stack.pop() + " ");
}
StdOut.println();
// print what's left on the stack
StdOut.print("Left on stack: ");
for (String s : stack) {
StdOut.print(s + " ");
}
StdOut.println();
}
}
|
/******************************************************************************
* Compilation: javac FixedCapacityStackOfStrings.java
* Execution: java FixedCapacityStackOfStrings
* Dependencies: StdIn.java StdOut.java
*
* Stack of strings implementation with a fixed-size array.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java FixedCapacityStackOfStrings 5 < tobe.txt
* to be not that or be
*
* Remark: bare-bones implementation. Does not do repeated
* doubling or null out empty array entries to avoid loitering.
*
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class FixedCapacityStackOfStrings implements Iterable<String> {
private String[] a; // holds the items
private int n; // number of items in stack
// create an empty stack with given capacity
public FixedCapacityStackOfStrings(int capacity) {
a = new String[capacity];
n = 0;
}
public boolean isEmpty() {
return n == 0;
}
public boolean isFull() {
return n == a.length;
}
public void push(String item) {
a[n++] = item;
}
public String pop() {
return a[--n];
}
public String peek() {
return a[n-1];
}
public Iterator<String> iterator() {
return new ReverseArrayIterator();
}
// an array iterator, in reverse order
public class ReverseArrayIterator implements Iterator<String> {
private int i = n-1;
public boolean hasNext() {
return i >= 0;
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
return a[i--];
}
}
public static void main(String[] args) {
int max = Integer.parseInt(args[0]);
FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) stack.push(item);
else if (stack.isEmpty()) StdOut.println("BAD INPUT");
else StdOut.print(stack.pop() + " ");
}
StdOut.println();
// print what's left on the stack
StdOut.print("Left on stack: ");
for (String s : stack) {
StdOut.print(s + " ");
}
StdOut.println();
}
}
|
[] |
{
"number": "1.3.1",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/FixedCapacityStackOfStrings.java",
"params": [
"5 < tobe.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Write a stack client Parentheses.java that reads in sequence of left and right parentheses, braces, and brackets from standard input and uses a stack to determine whether the sequence is properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]).
|
/******************************************************************************
* Compilation: javac Parentheses.java
* Execution: java Parentheses
* Dependencies: In.java Stack.java
*
* Reads in a text file and checks to see if the parentheses are balanced.
*
* % java Parentheses
* [()]{}{[()()]()}
* true
*
* % java Parentheses
* [(])
* false
*
******************************************************************************/
public class Parentheses {
private static final char LEFT_PAREN = '(';
private static final char RIGHT_PAREN = ')';
private static final char LEFT_BRACE = '{';
private static final char RIGHT_BRACE = '}';
private static final char LEFT_BRACKET = '[';
private static final char RIGHT_BRACKET = ']';
public static boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == LEFT_PAREN) stack.push(LEFT_PAREN);
if (s.charAt(i) == LEFT_BRACE) stack.push(LEFT_BRACE);
if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET);
if (s.charAt(i) == RIGHT_PAREN) {
if (stack.isEmpty()) return false;
if (stack.pop() != LEFT_PAREN) return false;
}
else if (s.charAt(i) == RIGHT_BRACE) {
if (stack.isEmpty()) return false;
if (stack.pop() != LEFT_BRACE) return false;
}
else if (s.charAt(i) == RIGHT_BRACKET) {
if (stack.isEmpty()) return false;
if (stack.pop() != LEFT_BRACKET) return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
In in = new In();
String s = in.readAll().trim();
StdOut.println(isBalanced(s));
}
}
|
[] |
{
"number": "1.3.4",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/Parentheses.java",
"params": [
"<<< \"[(])\"",
"<<< \"[()]{}{[()()]()}\""
],
"dependencies": [
"In.java",
"Stack.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Add a method peek to '/******************************************************************************
* Compilation: javac Stack.java
* Execution: java Stack < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic stack, implemented using a singly linked list.
* Each stack element is of type Item.
*
* This version uses a static nested class Node (to save 8 bytes per
* Node), whereas the version in the textbook uses a non-static nested
* class (for simplicity).
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java Stack < tobe.txt
* to be not that or be (2 left on stack)
*
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a singly linked list with a static nested class for
* linked-list nodes. See {@link LinkedStack} for the version from the
* textbook that uses a non-static nested class.
* See {@link ResizingArrayStack} for a version that uses a resizing array.
* The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param <Item> the generic type each item in this stack
*/
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack
// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}
/**
* Returns true if this stack is empty.
*
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in this stack.
*
* @return the number of items in this stack
*/
public int size() {
return n;
}
/**
* Adds the item to this stack.
*
* @param item the item to add
*/
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
/**
* Removes and returns the item most recently added to this stack.
*
* @return the item most recently added
* @throws NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
return item; // return the saved item
}
/**
* Returns (but does not remove) the item most recently added to this stack.
*
* @return the item most recently added to this stack
* @throws NoSuchElementException if this stack is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
}
/**
* Returns a string representation of this stack.
*
* @return the sequence of items in this stack in LIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this) {
s.append(item);
s.append(' ');
}
return s.toString();
}
/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
*
* @return an iterator to this stack that iterates through the items in LIFO order
*/
public Iterator<Item> iterator() {
return new LinkedIterator(first);
}
// the iterator
private class LinkedIterator implements Iterator<Item> {
private Node<Item> current;
public LinkedIterator(Node<Item> first) {
current = first;
}
// is there a next item?
public boolean hasNext() {
return current != null;
}
// returns the next item
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
/**
* Unit tests the {@code Stack} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
stack.push(item);
else if (!stack.isEmpty())
StdOut.print(stack.pop() + " ");
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}
' that returns the most recently inserted item on the stack (without popping it).
|
/******************************************************************************
* Compilation: javac Stack.java
* Execution: java Stack < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* A generic stack, implemented using a singly linked list.
* Each stack element is of type Item.
*
* This version uses a static nested class Node (to save 8 bytes per
* Node), whereas the version in the textbook uses a non-static nested
* class (for simplicity).
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java Stack < tobe.txt
* to be not that or be (2 left on stack)
*
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a singly linked list with a static nested class for
* linked-list nodes. See {@link LinkedStack} for the version from the
* textbook that uses a non-static nested class.
* See {@link ResizingArrayStack} for a version that uses a resizing array.
* The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param <Item> the generic type each item in this stack
*/
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack
// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}
/**
* Returns true if this stack is empty.
*
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in this stack.
*
* @return the number of items in this stack
*/
public int size() {
return n;
}
/**
* Adds the item to this stack.
*
* @param item the item to add
*/
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
/**
* Removes and returns the item most recently added to this stack.
*
* @return the item most recently added
* @throws NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
return item; // return the saved item
}
/**
* Returns (but does not remove) the item most recently added to this stack.
*
* @return the item most recently added to this stack
* @throws NoSuchElementException if this stack is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
}
/**
* Returns a string representation of this stack.
*
* @return the sequence of items in this stack in LIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this) {
s.append(item);
s.append(' ');
}
return s.toString();
}
/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
*
* @return an iterator to this stack that iterates through the items in LIFO order
*/
public Iterator<Item> iterator() {
return new LinkedIterator(first);
}
// the iterator
private class LinkedIterator implements Iterator<Item> {
private Node<Item> current;
public LinkedIterator(Node<Item> first) {
current = first;
}
// is there a next item?
public boolean hasNext() {
return current != null;
}
// returns the next item
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
/**
* Unit tests the {@code Stack} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
stack.push(item);
else if (!stack.isEmpty())
StdOut.print(stack.pop() + " ");
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}
|
[] |
{
"number": "1.3.7",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/Stack.java",
"params": [
"< tobe.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Write a filter Program InfixToPostfix.java that converts an arithmetic expression from infix to postfix.
|
/******************************************************************************
* Compilation: javac InfixToPostfix.java
* Execution: java InfixToPostFix
* Dependencies: Stack.java StdIn.java StdOut.java
*
* Reads in a fully parenthesized infix expression from standard input
* and prints an equivalent postfix expression to standard output.
*
* Windows users: replace [Ctrl-d] with [Ctrl-z] to signify end of file.
*
* % java InfixToPostfix
* ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )
* [Ctrl-d]
* 2 3 4 + 5 6 * * +
*
* % java InfixToPostfix
* ( ( ( 5 + ( 7 * ( 1 + 1 ) ) ) * 3 ) + ( 2 * ( 1 + 1 ) ) )
* 5 7 1 1 + * + 3 * 2 1 1 + * +
*
* % java InfixToPostfix | java EvaluatePostfix
* ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )
* [Ctrl-d]
* 212
*
******************************************************************************/
public class InfixToPostfix {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
while (!StdIn.isEmpty()) {
String s = StdIn.readString();
if (s.equals("+")) stack.push(s);
else if (s.equals("*")) stack.push(s);
else if (s.equals(")")) StdOut.print(stack.pop() + " ");
else if (s.equals("(")) StdOut.print("");
else StdOut.print(s + " ");
}
StdOut.println();
}
}
|
[] |
{
"number": "1.3.10",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/InfixToPostfix.java",
"params": [
"<<EOF\n( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )\nEOF",
"<<EOF\n( ( ( 5 + ( 7 * ( 1 + 1 ) ) ) * 3 ) + ( 2 * ( 1 + 1 ) ) )\nEOF"
],
"dependencies": [
"Stack.java",
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Write a program EvaluatePostfix.java that that takes a postfix expression from standard input, evaluates it, and prints the value.
|
/******************************************************************************
* Compilation: javac EvaluatePostfix.java
* Execution: java EvaluatePostfix < file.txt
* Dependencies: Stack.java StdIn.java StdOut.java
*
* Evaluates postfix expresions using a stack.
*
* Windows users: replace [Ctrl-d] with [Ctrl-z] to signify end of file.
*
* % java EvaluatePostfix
* 3 4 5 + *
* [Ctrl-d]
* 27
*
* % java EvaluatePostfix
* 1 2 3 4 5 * + 6 * * +
* [Ctrl-d]
* 277
*
* % java EvaluatePostfix
* 7 16 16 16 * * * 5 16 16 * * 3 16 * 1 + + +
* [Ctrl-d]
* 30001
*
* % java EvaluatePostfix
* 7 16 * 5 + 16 * 3 + 16 * 1 +
* [Ctrl-d]
* 30001
*
* Known bugs
* ----------
* - No error checking - assumes input is legal postfix expression.
* - All token must be separated by whitespace, e.g., 1 5+ is illegal.
*
******************************************************************************/
public class EvaluatePostfix {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
while (!StdIn.isEmpty()) {
String s = StdIn.readString();
if (s.equals("+")) stack.push(stack.pop() + stack.pop());
else if (s.equals("*")) stack.push(stack.pop() * stack.pop());
else stack.push(Integer.parseInt(s));
}
StdOut.println(stack.pop());
}
}
|
[] |
{
"number": "1.3.11",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/EvaluatePostfix.java",
"params": [
"<<EOF\n3 4 5 + *\nEOF",
"<<EOF\n1 2 3 4 5 * + 6 * * +\nEOF",
"<<EOF\n7 16 16 16 * * * 5 16 16 * * 3 16 * 1 + + +\nEOF",
"<<EOF\n7 16 * 5 + 16 * 3 + 16 * 1 +\nEOF"
],
"dependencies": [
"Stack.java",
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Develop a class ResizingArrayQueueOfStrings that implements the queue abstraction with a fixed-size array,
and then extend your implementation
to use array resizing
to remove the size restriction.
|
/******************************************************************************
* Compilation: javac ResizingArrayQueue.java
* Execution: java ResizingArrayQueue < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/13stacks/tobe.txt
*
* Queue implementation with a resizing array.
*
* % java ResizingArrayQueue < tobe.txt
* to be or not to be (2 left on queue)
*
******************************************************************************/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code ResizingArrayQueue} class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* This implementation uses a resizing array, which double the underlying array
* when it is full and halves the underlying array when it is one-quarter full.
* The <em>enqueue</em> and <em>dequeue</em> operations take constant amortized time.
* The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
* constant time in the worst case.
* <p>
* For additional documentation, see <a href="https://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class ResizingArrayQueue<Item> implements Iterable<Item> {
// initial capacity of underlying resizing array
private static final int INIT_CAPACITY = 8;
private Item[] q; // queue elements
private int n; // number of elements on queue
private int first; // index of first element of queue
private int last; // index of next available slot
/**
* Initializes an empty queue.
*/
public ResizingArrayQueue() {
q = (Item[]) new Object[INIT_CAPACITY];
n = 0;
first = 0;
last = 0;
}
/**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {
return n == 0;
}
/**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {
return n;
}
// resize the underlying array
private void resize(int capacity) {
assert capacity >= n;
Item[] copy = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
copy[i] = q[(first + i) % q.length];
}
q = copy;
first = 0;
last = n;
}
/**
* Adds the item to this queue.
* @param item the item to add
*/
public void enqueue(Item item) {
// double size of array if necessary and recopy to front of array
if (n == q.length) resize(2*q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
n++;
}
/**
* Removes and returns the item on this queue that was least recently added.
* @return the item on this queue that was least recently added
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = q[first];
q[first] = null; // to avoid loitering
n--;
first++;
if (first == q.length) first = 0; // wrap-around
// shrink size of array if necessary
if (n > 0 && n == q.length/4) resize(q.length/2);
return item;
}
/**
* Returns the item least recently added to this queue.
* @return the item least recently added to this queue
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return q[first];
}
/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ArrayIterator();
}
// an array iterator, from first to last-1
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
public boolean hasNext() {
return i < n;
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = q[(i + first) % q.length];
i++;
return item;
}
}
/**
* Unit tests the {@code ResizingArrayQueue} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
ResizingArrayQueue<String> queue = new ResizingArrayQueue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) queue.enqueue(item);
else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + " ");
}
StdOut.println("(" + queue.size() + " left on queue)");
}
}
|
[] |
{
"number": "1.3.14",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/ResizingArrayQueue.java",
"params": [
"< tobe.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Josephus problem. In the Josephus problem from antiquity, N people are in dire straits and agree to the following strategy to reduce the population. They arrange themselves in a circle (at positions numbered from 0 to N-1) and proceed around the circle, eliminating every Mth person until only one person is left. Legend has it that Josephus figured out where to sit to avoid being eliminated. Write a Queue client Josephus.java that takes M and N from the command line and prints out the order in which people are eliminated (and thus would show Josephus where to sit in the circle).
% java Josephus 2 7
1 3 5 0 4 2 6
|
/******************************************************************************
* Compilation: javac Josephus.java
* Execution: java Josephus m n
* Dependencies: Queue.java
*
* Solves the Josephus problem.
*
* % java Josephus 2 7
* 1 3 5 0 4 2 6
*
******************************************************************************/
public class Josephus {
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
// initialize the queue
Queue<Integer> queue = new Queue<Integer>();
for (int i = 0; i < n; i++)
queue.enqueue(i);
while (!queue.isEmpty()) {
for (int i = 0; i < m-1; i++)
queue.enqueue(queue.dequeue());
StdOut.print(queue.dequeue() + " ");
}
StdOut.println();
}
}
|
[] |
{
"number": "1.3.37",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/13stacks/Josephus.java",
"params": [
"2 7"
],
"dependencies": [
"Queue.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Develop classes QuickUnionUF.java that implement quick-union.
|
/******************************************************************************
* Compilation: javac QuickUnionUF.java
* Execution: java QuickUnionUF < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt
* https://algs4.cs.princeton.edu/15uf/mediumUF.txt
* https://algs4.cs.princeton.edu/15uf/largeUF.txt
*
* Quick-union algorithm.
*
******************************************************************************/
/**
* The {@code QuickUnionUF} class represents a <em>union–find data type</em>
* (also known as the <em>disjoint-sets data type</em>).
* It supports the classic <em>union</em> and <em>find</em> operations,
* along with a <em>count</em> operation that returns the total number
* of sets.
* <p>
* The union–find data type models a collection of sets containing
* <em>n</em> elements, with each element in exactly one set.
* The elements are named 0 through <em>n</em>–1.
* Initially, there are <em>n</em> sets, with each element in its
* own set. The <em>canonical element</em> of a set
* (also known as the <em>root</em>, <em>identifier</em>,
* <em>leader</em>, or <em>set representative</em>)
* is one distinguished element in the set. Here is a summary of
* the operations:
* <ul>
* <li><em>find</em>(<em>p</em>) returns the canonical element
* of the set containing <em>p</em>. The <em>find</em> operation
* returns the same value for two elements if and only if
* they are in the same set.
* <li><em>union</em>(<em>p</em>, <em>q</em>) merges the set
* containing element <em>p</em> with the set containing
* element <em>q</em>. That is, if <em>p</em> and <em>q</em>
* are in different sets, replace these two sets
* with a new set that is the union of the two.
* <li><em>count</em>() returns the number of sets.
* </ul>
* <p>
* The canonical element of a set can change only when the set
* itself changes during a call to <em>union</em>—it cannot
* change during a call to either <em>find</em> or <em>count</em>.
* <p>
* This implementation uses <em>quick union</em>.
* The constructor takes Θ(<em>n</em>) time, where
* <em>n</em> is the number of sites.
* The <em>union</em> and <em>find</em> operations take
* Θ(<em>n</em>) time in the worst case.
* The <em>count</em> operation takes Θ(1) time.
* <p>
* For alternative implementations of the same API, see
* {@link UF}, {@link QuickFindUF}, and {@link WeightedQuickUnionUF}.
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/15uf">Section 1.5</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class QuickUnionUF {
private int[] parent; // parent[i] = parent of i
private int count; // number of components
/**
* Initializes an empty union-find data structure with
* {@code n} elements {@code 0} through {@code n-1}.
* Initially, each element is in its own set.
*
* @param n the number of elements
* @throws IllegalArgumentException if {@code n < 0}
*/
public QuickUnionUF(int n) {
parent = new int[n];
count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
/**
* Returns the number of sets.
*
* @return the number of sets (between {@code 1} and {@code n})
*/
public int count() {
return count;
}
/**
* Returns the canonical element of the set containing element {@code p}.
*
* @param p an element
* @return the canonical element of the set containing {@code p}
* @throws IllegalArgumentException unless {@code 0 <= p < n}
*/
public int find(int p) {
validate(p);
while (p != parent[p])
p = parent[p];
return p;
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
/**
* Returns true if the two elements are in the same set.
*
* @param p one element
* @param q the other element
* @return {@code true} if {@code p} and {@code q} are in the same set;
* {@code false} otherwise
* @throws IllegalArgumentException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
* @deprecated Replace with two calls to {@link #find(int)}.
*/
@Deprecated
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/**
* Merges the set containing element {@code p} with the set
* containing element {@code q}.
*
* @param p one element
* @param q the other element
* @throws IllegalArgumentException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
parent[rootP] = rootQ;
count--;
}
/**
* Reads an integer {@code n} and a sequence of pairs of integers
* (between {@code 0} and {@code n-1}) from standard input, where each integer
* in the pair represents some element;
* if the elements are in different sets, merge the two sets
* and print the pair to standard output.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int n = StdIn.readInt();
QuickUnionUF uf = new QuickUnionUF(n);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.find(p) == uf.find(q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + " components");
}
}
|
[] |
{
"number": "1.5.7",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/15uf/QuickUnionUF.java",
"params": [
"< tinyUF.txt",
"< mediumUF.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Develop classes QuickFindUF.java that implement quick-find.
|
/******************************************************************************
* Compilation: javac QuickFindUF.java
* Execution: java QuickFindUF < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/15uf/tinyUF.txt
* https://algs4.cs.princeton.edu/15uf/mediumUF.txt
* https://algs4.cs.princeton.edu/15uf/largeUF.txt
*
* Quick-find algorithm.
*
******************************************************************************/
/**
* The {@code QuickFindUF} class represents a <em>union–find data type</em>
* (also known as the <em>disjoint-sets data type</em>).
* It supports the classic <em>union</em> and <em>find</em> operations,
* along with a <em>count</em> operation that returns the total number
* of sets.
* <p>
* The union–find data type models a collection of sets containing
* <em>n</em> elements, with each element in exactly one set.
* The elements are named 0 through <em>n</em>–1.
* Initially, there are <em>n</em> sets, with each element in its
* own set. The <em>canonical element</em> of a set
* (also known as the <em>root</em>, <em>identifier</em>,
* <em>leader</em>, or <em>set representative</em>)
* is one distinguished element in the set. Here is a summary of
* the operations:
* <ul>
* <li><em>find</em>(<em>p</em>) returns the canonical element
* of the set containing <em>p</em>. The <em>find</em> operation
* returns the same value for two elements if and only if
* they are in the same set.
* <li><em>union</em>(<em>p</em>, <em>q</em>) merges the set
* containing element <em>p</em> with the set containing
* element <em>q</em>. That is, if <em>p</em> and <em>q</em>
* are in different sets, replace these two sets
* with a new set that is the union of the two.
* <li><em>count</em>() returns the number of sets.
* </ul>
* <p>
* The canonical element of a set can change only when the set
* itself changes during a call to <em>union</em>—it cannot
* change during a call to either <em>find</em> or <em>count</em>.
* <p>
* This implementation uses <em>quick find</em>.
* The constructor takes Θ(<em>n</em>) time, where <em>n</em>
* is the number of sites.
* The <em>find</em>, <em>connected</em>, and <em>count</em>
* operations take Θ(1) time; the <em>union</em> operation
* takes Θ(<em>n</em>) time.
* <p>
* For alternative implementations of the same API, see
* {@link UF}, {@link QuickUnionUF}, and {@link WeightedQuickUnionUF}.
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/15uf">Section 1.5</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class QuickFindUF {
private int[] id; // id[i] = component identifier of i
private int count; // number of components
/**
* Initializes an empty union-find data structure with
* {@code n} elements {@code 0} through {@code n-1}.
* Initially, each element is in its own set.
*
* @param n the number of elements
* @throws IllegalArgumentException if {@code n < 0}
*/
public QuickFindUF(int n) {
count = n;
id = new int[n];
for (int i = 0; i < n; i++)
id[i] = i;
}
/**
* Returns the number of sets.
*
* @return the number of sets (between {@code 1} and {@code n})
*/
public int count() {
return count;
}
/**
* Returns the canonical element of the set containing element {@code p}.
*
* @param p an element
* @return the canonical element of the set containing {@code p}
* @throws IllegalArgumentException unless {@code 0 <= p < n}
*/
public int find(int p) {
validate(p);
return id[p];
}
// validate that p is a valid index
private void validate(int p) {
int n = id.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
/**
* Returns true if the two elements are in the same set.
*
* @param p one element
* @param q the other element
* @return {@code true} if {@code p} and {@code q} are in the same set;
* {@code false} otherwise
* @throws IllegalArgumentException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
* @deprecated Replace with two calls to {@link #find(int)}.
*/
@Deprecated
public boolean connected(int p, int q) {
validate(p);
validate(q);
return id[p] == id[q];
}
/**
* Merges the set containing element {@code p} with the set
* containing element {@code q}.
*
* @param p one element
* @param q the other element
* @throws IllegalArgumentException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public void union(int p, int q) {
validate(p);
validate(q);
int pID = id[p]; // needed for correctness
int qID = id[q]; // to reduce the number of array accesses
// p and q are already in the same component
if (pID == qID) return;
for (int i = 0; i < id.length; i++)
if (id[i] == pID) id[i] = qID;
count--;
}
/**
* Reads an integer {@code n} and a sequence of pairs of integers
* (between {@code 0} and {@code n-1}) from standard input, where each integer
* in the pair represents some element;
* if the elements are in different sets, merge the two sets
* and print the pair to standard output.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int n = StdIn.readInt();
QuickFindUF uf = new QuickFindUF(n);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.find(p) == uf.find(q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + " components");
}
}
|
[] |
{
"number": "1.5.7",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/15uf/QuickFindUF.java",
"params": [
"< tinyUF.txt",
"< mediumUF.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Transaction sort test client. Write a class SortTransactions.java that consists of a static method main() that reads a sequence of transactions from standard
input, sorts them, and prints the result on standard output.
|
/******************************************************************************
* Compilation: javac SortTransactions.java
* Execution: java SortTransactions < input.txt
* Dependencies: StdOut.java
* Data file: https://algs4.cs.princeton.edu/21elementary/tinyBatch.txt
*
* % java SortTransactions < transactions.txt
* Turing 1/11/2002 66.10
* Knuth 6/14/1999 288.34
* Turing 6/17/1990 644.08
* Dijkstra 9/10/2000 708.95
* Dijkstra 11/18/1995 837.42
* Hoare 8/12/2003 1025.70
* Bellman 10/26/2007 1358.62
* Knuth 7/25/2008 1564.55
* Turing 2/11/1991 2156.86
* Tarjan 10/13/1993 2520.97
* Dijkstra 8/22/2007 2678.40
* Hoare 5/10/1993 3229.27
* Knuth 11/11/2008 3284.33
* Turing 10/12/1993 3532.36
* Hoare 2/10/2005 4050.20
* Tarjan 3/26/2002 4121.85
* Hoare 8/18/1992 4381.21
* Tarjan 1/11/1999 4409.74
* Tarjan 2/12/1994 4732.35
* Thompson 2/27/2000 4747.08
*
******************************************************************************/
import java.util.Arrays;
public class SortTransactions {
public static Transaction[] readTransactions() {
Queue<Transaction> queue = new Queue<Transaction>();
while (StdIn.hasNextLine()) {
String line = StdIn.readLine();
Transaction transaction = new Transaction(line);
queue.enqueue(transaction);
}
int n = queue.size();
Transaction[] transactions = new Transaction[n];
for (int i = 0; i < n; i++)
transactions[i] = queue.dequeue();
return transactions;
}
public static void main(String[] args) {
Transaction[] transactions = readTransactions();
Arrays.sort(transactions);
for (int i = 0; i < transactions.length; i++)
StdOut.println(transactions[i]);
}
}
|
[] |
{
"number": "2.1.22",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/21elementary/SortTransactions.java",
"params": [
"< tinyBatch.txt"
],
"dependencies": [
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Insertion sort with sentinel. Develop an implementation InsertionX.java of insertion sort that eliminates the j > 0 test in the inner loop by first putting the smallest item into position
|
/******************************************************************************
* Compilation: javac InsertionX.java
* Execution: java InsertionX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt
* https://algs4.cs.princeton.edu/21elementary/words3.txt
*
* Sorts a sequence of strings from standard input using an optimized
* version of insertion sort that uses half exchanges instead of
* full exchanges to reduce data movement..
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java InsertionX < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java InsertionX < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
/**
* The {@code InsertionX} class provides static methods for sorting
* an array using an optimized version of insertion sort (with half exchanges
* and a sentinel).
* <p>
* In the worst case, this implementation makes ~ 1/2 <em>n</em><sup>2</sup>
* compares to sort an array of length <em>n</em>.
* So, it is not suitable for sorting large arrays
* (unless the number of inversions is small).
* <p>
* This sorting algorithm is stable.
* It uses Θ(1) extra memory (not including the input array).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class InsertionX {
// This class should not be instantiated.
private InsertionX() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
int n = a.length;
// put smallest element in position to serve as sentinel
int exchanges = 0;
for (int i = n-1; i > 0; i--) {
if (less(a[i], a[i-1])) {
exch(a, i, i-1);
exchanges++;
}
}
if (exchanges == 0) return;
// insertion sort with half-exchanges
for (int i = 2; i < n; i++) {
Comparable v = a[i];
int j = i;
while (less(v, a[j-1])) {
a[j] = a[j-1];
j--;
}
a[j] = v;
}
assert isSorted(a);
}
/***************************************************************************
* Helper sorting functions.
***************************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; insertion sorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
InsertionX.sort(a);
show(a);
}
}
|
[] |
{
"number": "2.1.23",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/21elementary/InsertionX.java",
"params": [
"< words3.txt",
"< tiny.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Insertion sort without exchanges. Develop an implementation InsertionX.java of insertion sort that moves larger items to the right one position rather
than doing full exchanges.
|
/******************************************************************************
* Compilation: javac InsertionX.java
* Execution: java InsertionX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt
* https://algs4.cs.princeton.edu/21elementary/words3.txt
*
* Sorts a sequence of strings from standard input using an optimized
* version of insertion sort that uses half exchanges instead of
* full exchanges to reduce data movement..
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java InsertionX < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java InsertionX < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
/**
* The {@code InsertionX} class provides static methods for sorting
* an array using an optimized version of insertion sort (with half exchanges
* and a sentinel).
* <p>
* In the worst case, this implementation makes ~ 1/2 <em>n</em><sup>2</sup>
* compares to sort an array of length <em>n</em>.
* So, it is not suitable for sorting large arrays
* (unless the number of inversions is small).
* <p>
* This sorting algorithm is stable.
* It uses Θ(1) extra memory (not including the input array).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class InsertionX {
// This class should not be instantiated.
private InsertionX() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
int n = a.length;
// put smallest element in position to serve as sentinel
int exchanges = 0;
for (int i = n-1; i > 0; i--) {
if (less(a[i], a[i-1])) {
exch(a, i, i-1);
exchanges++;
}
}
if (exchanges == 0) return;
// insertion sort with half-exchanges
for (int i = 2; i < n; i++) {
Comparable v = a[i];
int j = i;
while (less(v, a[j-1])) {
a[j] = a[j-1];
j--;
}
a[j] = v;
}
assert isSorted(a);
}
/***************************************************************************
* Helper sorting functions.
***************************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; insertion sorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
InsertionX.sort(a);
show(a);
}
}
|
[] |
{
"number": "2.1.24",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/21elementary/InsertionX.java",
"params": [
"< words3.txt",
"< tiny.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
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.java that
does not use a static array.
|
/******************************************************************************
* Compilation: javac Merge.java
* Execution: java Merge < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt
* https://algs4.cs.princeton.edu/22mergesort/words3.txt
*
* Sorts a sequence of strings from standard input using mergesort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Merge < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Merge < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
/**
* The {@code Merge} class provides static methods for sorting an
* array using a top-down, recursive version of <em>mergesort</em>.
* <p>
* This implementation takes Θ(<em>n</em> log <em>n</em>) time
* to sort any array of length <em>n</em> (assuming comparisons
* take constant time). It makes between
* ~ ½ <em>n</em> log<sub>2</sub> <em>n</em> and
* ~ 1 <em>n</em> log<sub>2</sub> <em>n</em> compares.
* <p>
* This sorting algorithm is stable.
* It uses Θ(<em>n</em>) extra memory (not including the input array).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* For an optimized version, see {@link MergeX}.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Merge {
// This class should not be instantiated.
private Merge() { }
// stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]
private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
// precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays
assert isSorted(a, lo, mid);
assert isSorted(a, mid+1, hi);
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) a[k] = aux[j++];
else a[k] = aux[i++];
}
// postcondition: a[lo .. hi] is sorted
assert isSorted(a, lo, hi);
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
}
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length-1);
assert isSorted(a);
}
/***************************************************************************
* Helper sorting function.
***************************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
/***************************************************************************
* Index mergesort.
***************************************************************************/
// stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) {
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = index[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) index[k] = aux[j++];
else if (j > hi) index[k] = aux[i++];
else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];
else index[k] = aux[i++];
}
}
/**
* Returns a permutation that gives the elements in the array in ascending order.
* @param a the array
* @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},
* ..., {@code a[p[n-1]]} are in ascending order
*/
public static int[] indexSort(Comparable[] a) {
int n = a.length;
int[] index = new int[n];
for (int i = 0; i < n; i++)
index[i] = i;
int[] aux = new int[n];
sort(a, index, aux, 0, n-1);
return index;
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, index, aux, lo, mid);
sort(a, index, aux, mid + 1, hi);
merge(a, index, aux, lo, mid, hi);
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; mergesorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Merge.sort(a);
show(a);
}
}
|
[] |
{
"number": "2.2.9",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/22mergesort/Merge.java",
"params": [
"< tiny.txt",
"< words3.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Improvements. Write a program MergeX.java that implements the three improvements to mergesort that are described in the text: add a cutoff from small subarrays, test whether the array is already in order, and avoid the copy by switching arguments in the recursive code
|
/******************************************************************************
* Compilation: javac MergeX.java
* Execution: java MergeX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt
* https://algs4.cs.princeton.edu/22mergesort/words3.txt
*
* Sorts a sequence of strings from standard input using an
* optimized version of mergesort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java MergeX < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java MergeX < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
import java.util.Comparator;
/**
* The {@code MergeX} class provides static methods for sorting an
* array using an optimized version of mergesort.
* <p>
* In the worst case, this implementation takes
* Θ(<em>n</em> log <em>n</em>) time to sort an array of
* length <em>n</em> (assuming comparisons take constant time).
* <p>
* This sorting algorithm is stable.
* It uses Θ(<em>n</em>) extra memory (not including the input array).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class MergeX {
private static final int CUTOFF = 7; // cutoff to insertion sort
// This class should not be instantiated.
private MergeX() { }
private static void merge(Comparable[] src, Comparable[] dst, int lo, int mid, int hi) {
// precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays
assert isSorted(src, lo, mid);
assert isSorted(src, mid+1, hi);
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) dst[k] = src[j++];
else if (j > hi) dst[k] = src[i++];
else if (less(src[j], src[i])) dst[k] = src[j++]; // to ensure stability
else dst[k] = src[i++];
}
// postcondition: dst[lo .. hi] is sorted subarray
assert isSorted(dst, lo, hi);
}
private static void sort(Comparable[] src, Comparable[] dst, int lo, int hi) {
// if (hi <= lo) return;
if (hi <= lo + CUTOFF) {
insertionSort(dst, lo, hi);
return;
}
int mid = lo + (hi - lo) / 2;
sort(dst, src, lo, mid);
sort(dst, src, mid+1, hi);
// if (!less(src[mid+1], src[mid])) {
// for (int i = lo; i <= hi; i++) dst[i] = src[i];
// return;
// }
// using System.arraycopy() is a bit faster than the above loop
if (!less(src[mid+1], src[mid])) {
System.arraycopy(src, lo, dst, lo, hi - lo + 1);
return;
}
merge(src, dst, lo, mid, hi);
}
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
Comparable[] aux = a.clone();
sort(aux, a, 0, a.length-1);
assert isSorted(a);
}
// sort from a[lo] to a[hi] using insertion sort
private static void insertionSort(Comparable[] a, int lo, int hi) {
for (int i = lo; i <= hi; i++)
for (int j = i; j > lo && less(a[j], a[j-1]); j--)
exch(a, j, j-1);
}
/*******************************************************************
* Utility methods.
*******************************************************************/
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// is a[i] < a[j]?
private static boolean less(Comparable a, Comparable b) {
return a.compareTo(b) < 0;
}
// is a[i] < a[j]?
private static boolean less(Object a, Object b, Comparator comparator) {
return comparator.compare(a, b) < 0;
}
/*******************************************************************
* Version that takes Comparator as argument.
*******************************************************************/
/**
* Rearranges the array in ascending order, using the provided order.
*
* @param a the array to be sorted
* @param comparator the comparator that defines the total order
*/
public static void sort(Object[] a, Comparator comparator) {
Object[] aux = a.clone();
sort(aux, a, 0, a.length-1, comparator);
assert isSorted(a, comparator);
}
private static void merge(Object[] src, Object[] dst, int lo, int mid, int hi, Comparator comparator) {
// precondition: src[lo .. mid] and src[mid+1 .. hi] are sorted subarrays
assert isSorted(src, lo, mid, comparator);
assert isSorted(src, mid+1, hi, comparator);
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) dst[k] = src[j++];
else if (j > hi) dst[k] = src[i++];
else if (less(src[j], src[i], comparator)) dst[k] = src[j++];
else dst[k] = src[i++];
}
// postcondition: dst[lo .. hi] is sorted subarray
assert isSorted(dst, lo, hi, comparator);
}
private static void sort(Object[] src, Object[] dst, int lo, int hi, Comparator comparator) {
// if (hi <= lo) return;
if (hi <= lo + CUTOFF) {
insertionSort(dst, lo, hi, comparator);
return;
}
int mid = lo + (hi - lo) / 2;
sort(dst, src, lo, mid, comparator);
sort(dst, src, mid+1, hi, comparator);
// using System.arraycopy() is a bit faster than the above loop
if (!less(src[mid+1], src[mid], comparator)) {
System.arraycopy(src, lo, dst, lo, hi - lo + 1);
return;
}
merge(src, dst, lo, mid, hi, comparator);
}
// sort from a[lo] to a[hi] using insertion sort
private static void insertionSort(Object[] a, int lo, int hi, Comparator comparator) {
for (int i = lo; i <= hi; i++)
for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--)
exch(a, j, j-1);
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
private static boolean isSorted(Object[] a, Comparator comparator) {
return isSorted(a, 0, a.length - 1, comparator);
}
private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1], comparator)) return false;
return true;
}
// print array to standard output
private static void show(Object[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; mergesorts them
* (using an optimized version of mergesort);
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
MergeX.sort(a);
show(a);
}
}
|
[] |
{
"number": "2.2.11",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/22mergesort/MergeX.java",
"params": [
"< tiny.txt",
"< words3.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Inversions. Develop and implement a linearithmic algorithm Inversions.java for computing the number of inversions in a given array (the number of exchanges that would be performed by insertion sort for that array—see Section 2.1). This quantity is related to the Kendall tau distance
|
/******************************************************************************
* Compilation: javac Inversions.java
* Execution: java Inversions < input.txt
* Dependencies: StdIn.java StdOut.java
*
* Read array of n integers and count number of inversions in n log n time.
*
******************************************************************************/
/**
* The {@code Inversions} class provides static methods to count the
* number of <em>inversions</em> in either an array of integers or comparables.
* An inversion in an array {@code a[]} is a pair of indicies {@code i} and
* {@code j} such that {@code i < j} and {@code a[i] > a[j]}.
* <p>
* This implementation uses a generalization of mergesort. The <em>count</em>
* operation takes Θ(<em>n</em> log <em>n</em>) time to count the
* number of inversions in any array of length <em>n</em> (assuming
* comparisons take constant time).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a>
* of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Inversions {
// do not instantiate
private Inversions() { }
// merge and count
private static long merge(int[] a, int[] aux, int lo, int mid, int hi) {
long inversions = 0;
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (aux[j] < aux[i]) { a[k] = aux[j++]; inversions += (mid - i + 1); }
else a[k] = aux[i++];
}
return inversions;
}
// return the number of inversions in the subarray b[lo..hi]
// side effect b[lo..hi] is rearranged in ascending order
private static long count(int[] a, int[] b, int[] aux, int lo, int hi) {
long inversions = 0;
if (hi <= lo) return 0;
int mid = lo + (hi - lo) / 2;
inversions += count(a, b, aux, lo, mid);
inversions += count(a, b, aux, mid+1, hi);
inversions += merge(b, aux, lo, mid, hi);
assert inversions == brute(a, lo, hi);
return inversions;
}
/**
* Returns the number of inversions in the integer array.
* The argument array is not modified.
* @param a the array
* @return the number of inversions in the array. An inversion is a pair of
* indicies {@code i} and {@code j} such that {@code i < j}
* and {@code a[i] > a[j]}.
*/
public static long count(int[] a) {
int[] b = new int[a.length];
int[] aux = new int[a.length];
for (int i = 0; i < a.length; i++)
b[i] = a[i];
long inversions = count(a, b, aux, 0, a.length - 1);
return inversions;
}
// merge and count (Comparable version)
private static <Key extends Comparable<Key>> long merge(Key[] a, Key[] aux, int lo, int mid, int hi) {
long inversions = 0;
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) { a[k] = aux[j++]; inversions += (mid - i + 1); }
else a[k] = aux[i++];
}
return inversions;
}
// return the number of inversions in the subarray b[lo..hi]
// side effect b[lo..hi] is rearranged in ascending order
private static <Key extends Comparable<Key>> long count(Key[] a, Key[] b, Key[] aux, int lo, int hi) {
long inversions = 0;
if (hi <= lo) return 0;
int mid = lo + (hi - lo) / 2;
inversions += count(a, b, aux, lo, mid);
inversions += count(a, b, aux, mid+1, hi);
inversions += merge(b, aux, lo, mid, hi);
assert inversions == brute(a, lo, hi);
return inversions;
}
/**
* Returns the number of inversions in the comparable array.
* The argument array is not modified.
* @param a the array
* @param <Key> the inferred type of the elements in the array
* @return the number of inversions in the array. An inversion is a pair of
* indicies {@code i} and {@code j} such that {@code i < j}
* and {@code a[i].compareTo(a[j]) > 0}.
*/
public static <Key extends Comparable<Key>> long count(Key[] a) {
Key[] b = a.clone();
Key[] aux = a.clone();
long inversions = count(a, b, aux, 0, a.length - 1);
return inversions;
}
// is v < w ?
private static <Key extends Comparable<Key>> boolean less(Key v, Key w) {
return (v.compareTo(w) < 0);
}
// count number of inversions in a[lo..hi] via brute force (for debugging only)
private static <Key extends Comparable<Key>> long brute(Key[] a, int lo, int hi) {
long inversions = 0;
for (int i = lo; i <= hi; i++)
for (int j = i + 1; j <= hi; j++)
if (less(a[j], a[i])) inversions++;
return inversions;
}
// count number of inversions in a[lo..hi] via brute force (for debugging only)
private static long brute(int[] a, int lo, int hi) {
long inversions = 0;
for (int i = lo; i <= hi; i++)
for (int j = i + 1; j <= hi; j++)
if (a[j] < a[i]) inversions++;
return inversions;
}
/**
* Reads a sequence of integers from standard input and
* prints the number of inversions to standard output.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int[] a = StdIn.readAllInts();
int n = a.length;
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++)
b[i] = a[i];
StdOut.println(Inversions.count(a));
StdOut.println(Inversions.count(b));
}
}
|
[] |
{
"number": "2.2.19",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/22mergesort/Inversions.java",
"params": [
"< 1Kints.txt",
"< 2Kints.txt",
"< 4Kints.txt",
"< 8Kints.txt",
"< 16Kints.txt",
"< 32Kints.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Index sort. Develop a version of Merge.java that does not rearrange the array, but returns an int[] perm such that perm[i] is the index of the ith smallest entry in the array.
|
/******************************************************************************
* Compilation: javac Merge.java
* Execution: java Merge < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt
* https://algs4.cs.princeton.edu/22mergesort/words3.txt
*
* Sorts a sequence of strings from standard input using mergesort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Merge < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Merge < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
/**
* The {@code Merge} class provides static methods for sorting an
* array using a top-down, recursive version of <em>mergesort</em>.
* <p>
* This implementation takes Θ(<em>n</em> log <em>n</em>) time
* to sort any array of length <em>n</em> (assuming comparisons
* take constant time). It makes between
* ~ ½ <em>n</em> log<sub>2</sub> <em>n</em> and
* ~ 1 <em>n</em> log<sub>2</sub> <em>n</em> compares.
* <p>
* This sorting algorithm is stable.
* It uses Θ(<em>n</em>) extra memory (not including the input array).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/22mergesort">Section 2.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* For an optimized version, see {@link MergeX}.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Merge {
// This class should not be instantiated.
private Merge() { }
// stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]
private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
// precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays
assert isSorted(a, lo, mid);
assert isSorted(a, mid+1, hi);
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) a[k] = aux[j++];
else a[k] = aux[i++];
}
// postcondition: a[lo .. hi] is sorted
assert isSorted(a, lo, hi);
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
}
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length-1);
assert isSorted(a);
}
/***************************************************************************
* Helper sorting function.
***************************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
/***************************************************************************
* Index mergesort.
***************************************************************************/
// stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) {
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = index[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) index[k] = aux[j++];
else if (j > hi) index[k] = aux[i++];
else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];
else index[k] = aux[i++];
}
}
/**
* Returns a permutation that gives the elements in the array in ascending order.
* @param a the array
* @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},
* ..., {@code a[p[n-1]]} are in ascending order
*/
public static int[] indexSort(Comparable[] a) {
int n = a.length;
int[] index = new int[n];
for (int i = 0; i < n; i++)
index[i] = i;
int[] aux = new int[n];
sort(a, index, aux, 0, n-1);
return index;
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, index, aux, lo, mid);
sort(a, index, aux, mid + 1, hi);
merge(a, index, aux, lo, mid, hi);
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; mergesorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Merge.sort(a);
show(a);
}
}
|
[] |
{
"number": "2.2.20",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/22mergesort/Merge.java",
"params": [
"< tiny.txt",
"< words3.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Write a program Sort2distinct.java that sorts an array that is known to contain just two distinct key values.
|
/******************************************************************************
* Compilation: javac Sort2distinct.java
* Execution: java Sort2distinct binary-string
* Dependencies: StdOut.java
*
* Partitions the array of specified as the command-line.
* Assumes there are at most 2 distinct elements.
*
******************************************************************************/
public class Sort2distinct {
// rearranges a[] in ascending order assuming a[] has at most 3 distinct values
public static void sort(Comparable[] a) {
int lt = 0, gt = a.length - 1;
int i = 0;
while (i <= gt) {
int cmp = a[i].compareTo(a[lt]);
if (cmp < 0) exch(a, lt++, i++);
else if (cmp > 0) exch(a, i, gt--);
else i++;
}
}
// exchange a[i] and a[j]
private static void exch(Comparable[] a, int i, int j) {
Comparable swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// test client
public static void main(String[] args) {
// parse command-line argument as an array of 1-character strings
String s = args[0];
int n = s.length();
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = s.substring(i, i+1);
// sort a print results
sort(a);
for (int i = 0; i < n; i++)
StdOut.print(a[i]);
StdOut.println();
}
}
|
[] |
{
"number": "2.3.5",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/23quicksort/Sort2distinct.java",
"params": [
"01001111011100111011011101001100",
"10110111001101111100001011011011",
"10110100010000111011000111110000",
"01110100010010011010011111001001",
"11000101001001011100011011010111"
],
"dependencies": [
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Best case. Write a program QuickBest.java that produces a best-case array (with no duplicates) for Quick.sort(): an array of N distinct keys with the property that every partition will produce subarrays that differ in size by at most 1 (the same subarray sizes that would happen for an array of N equal keys). For the purposes of this exercise, ignore the initial shuffle.
|
/******************************************************************************
* Compilation: javac QuickBest.java
* Execution: java QuickBest n
* Dependencies: StdOut.java
*
* Generate a best-case input of size n for standard quicksort.
*
* % java QuickBest 3
* BAC
*
* % java QuickBest 7
* DACBFEG
*
* % java QuickBest 15
* HACBFEGDLIKJNMO
*
******************************************************************************/
public class QuickBest {
// postcondition: a[lo..hi] is best-case input for quicksorting that subarray
private static void best(int[] a, int lo, int hi) {
// precondition: a[lo..hi] contains keys lo to hi, in order
for (int i = lo; i <= hi; i++)
assert a[i] == i;
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
best(a, lo, mid-1);
best(a, mid+1, hi);
exch(a, lo, mid);
}
public static int[] best(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = i;
best(a, 0, n-1);
return a;
}
// exchange a[i] and a[j]
private static void exch(int[] a, int i, int j) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int n = Integer.parseInt(args[0]);
int[] a = best(n);
for (int i = 0; i < n; i++)
// StdOut.println(a[i]);
StdOut.print(alphabet.charAt(a[i]));
StdOut.println();
}
}
|
[] |
{
"number": "2.3.16",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/23quicksort/QuickBest.java",
"params": [
"3",
"7",
"15"
],
"dependencies": [
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Fast three-way partitioning. (J. Bentley and D. McIlroy). Implement an entropy-optimal sort QuickBentleyMcIlroy.java based on keeping equal keys at both the left and right ends of the subarray. Maintain indices p and q such that a[lo..p-1] that a[q+1..hi] are all equal to a[lo], an index i such that a[p..i-1] are all less than a[lo] and an index j such that a[j+1..q] are all greater than a[lo]. Add to the inner partitioning loop code to swap a[i] with a[p] (and increment p) if it is equal to v and to swap a[j] with a[q] (and decrement q) if it is equal to v before the usual comparisons of a[i] and a[j] with v. After the partitioning loop has terminated, add code to swap the equal keys into position
|
/******************************************************************************
* Compilation: javac QuickX.java
* Execution: java QuickX < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt
* https://algs4.cs.princeton.edu/23quicksort/words3.txt
*
* Uses the Hoare's 2-way partitioning scheme, chooses the partitioning
* element using median-of-3, and cuts off to insertion sort.
*
******************************************************************************/
/**
* The {@code QuickX} class provides static methods for sorting an array
* using an optimized version of quicksort (using Hoare's 2-way partitioning
* algorithm, median-of-3 to choose the partitioning element, and cutoff
* to insertion sort).
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/23quicksort">Section 2.3</a>
* of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class QuickX {
// cutoff to insertion sort, must be >= 1
private static final int INSERTION_SORT_CUTOFF = 8;
// This class should not be instantiated.
private QuickX() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
// StdRandom.shuffle(a);
sort(a, 0, a.length - 1);
assert isSorted(a);
}
// quicksort the subarray from a[lo] to a[hi]
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) return;
// cutoff to insertion sort (Insertion.sort() uses half-open intervals)
int n = hi - lo + 1;
if (n <= INSERTION_SORT_CUTOFF) {
Insertion.sort(a, lo, hi + 1);
return;
}
int j = partition(a, lo, hi);
sort(a, lo, j-1);
sort(a, j+1, hi);
}
// partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi]
// and return the index j.
private static int partition(Comparable[] a, int lo, int hi) {
int n = hi - lo + 1;
int m = median3(a, lo, lo + n/2, hi);
exch(a, m, lo);
int i = lo;
int j = hi + 1;
Comparable v = a[lo];
// a[lo] is unique largest element
while (less(a[++i], v)) {
if (i == hi) { exch(a, lo, hi); return hi; }
}
// a[lo] is unique smallest element
while (less(v, a[--j])) {
if (j == lo + 1) return lo;
}
// the main loop
while (i < j) {
exch(a, i, j);
while (less(a[++i], v)) ;
while (less(v, a[--j])) ;
}
// put partitioning item v at a[j]
exch(a, lo, j);
// now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]
return j;
}
// return the index of the median element among a[i], a[j], and a[k]
private static int median3(Comparable[] a, int i, int j, int k) {
return (less(a[i], a[j]) ?
(less(a[j], a[k]) ? j : less(a[i], a[k]) ? k : i) :
(less(a[k], a[j]) ? j : less(a[k], a[i]) ? k : i));
}
/***************************************************************************
* Helper sorting functions.
***************************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; quicksorts them
* (using an optimized version of 2-way quicksort);
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
QuickX.sort(a);
assert isSorted(a);
show(a);
}
}
|
[] |
{
"number": "2.3.22",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/23quicksort/QuickX.java",
"params": [
"< tiny.txt",
"< words3.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.
|
/******************************************************************************
* Compilation: javac MaxPQ.java
* Execution: java MaxPQ < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/24pq/tinyPQ.txt
*
* Generic max priority queue implementation with a binary heap.
* Can be used with a comparator instead of the natural order,
* but the generic Key type must still be Comparable.
*
* % java MaxPQ < tinyPQ.txt
* Q X P (6 left on pq)
*
* We use a one-based array to simplify parent and child calculations.
*
* Can be optimized by replacing full exchanges with half exchanges
* (ala insertion sort).
*
******************************************************************************/
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code MaxPQ} class represents a priority queue of generic keys.
* It supports the usual <em>insert</em> and <em>delete-the-maximum</em>
* operations, along with methods for peeking at the maximum key,
* testing if the priority queue is empty, and iterating through
* the keys.
* <p>
* This implementation uses a <em>binary heap</em>.
* The <em>insert</em> and <em>delete-the-maximum</em> operations take
* Θ(log <em>n</em>) amortized time, where <em>n</em> is the number
* of elements in the priority queue. This is an amortized bound
* (and not a worst-case bound) because of array resizing operations.
* The <em>min</em>, <em>size</em>, and <em>is-empty</em> operations take
* Θ(1) time in the worst case.
* Construction takes time proportional to the specified capacity or the
* number of items used to initialize the data structure.
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/24pq">Section 2.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param <Key> the generic type of key on this priority queue
*/
public class MaxPQ<Key> implements Iterable<Key> {
private Key[] pq; // store items at indices 1 to n
private int n; // number of items on priority queue
private Comparator<Key> comparator; // optional comparator
/**
* Initializes an empty priority queue with the given initial capacity.
*
* @param initCapacity the initial capacity of this priority queue
*/
public MaxPQ(int initCapacity) {
pq = (Key[]) new Object[initCapacity + 1];
n = 0;
}
/**
* Initializes an empty priority queue.
*/
public MaxPQ() {
this(1);
}
/**
* Initializes an empty priority queue with the given initial capacity,
* using the given comparator.
*
* @param initCapacity the initial capacity of this priority queue
* @param comparator the order in which to compare the keys
*/
public MaxPQ(int initCapacity, Comparator<Key> comparator) {
this.comparator = comparator;
pq = (Key[]) new Object[initCapacity + 1];
n = 0;
}
/**
* Initializes an empty priority queue using the given comparator.
*
* @param comparator the order in which to compare the keys
*/
public MaxPQ(Comparator<Key> comparator) {
this(1, comparator);
}
/**
* Initializes a priority queue from the array of keys.
* Takes time proportional to the number of keys, using sink-based heap construction.
*
* @param keys the array of keys
*/
public MaxPQ(Key[] keys) {
n = keys.length;
pq = (Key[]) new Object[keys.length + 1];
for (int i = 0; i < n; i++)
pq[i+1] = keys[i];
for (int k = n/2; k >= 1; k--)
sink(k);
assert isMaxHeap();
}
/**
* Returns true if this priority queue is empty.
*
* @return {@code true} if this priority queue is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return n == 0;
}
/**
* Returns the number of keys on this priority queue.
*
* @return the number of keys on this priority queue
*/
public int size() {
return n;
}
/**
* Returns a largest key on this priority queue.
*
* @return a largest key on this priority queue
* @throws NoSuchElementException if this priority queue is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
// resize the underlying array to have the given capacity
private void resize(int capacity) {
assert capacity > n;
Key[] temp = (Key[]) new Object[capacity];
for (int i = 1; i <= n; i++) {
temp[i] = pq[i];
}
pq = temp;
}
/**
* Adds a new key to this priority queue.
*
* @param x the new key to add to this priority queue
*/
public void insert(Key x) {
// double size of array if necessary
if (n == pq.length - 1) resize(2 * pq.length);
// add x, and percolate it up to maintain heap invariant
pq[++n] = x;
swim(n);
assert isMaxHeap();
}
/**
* Removes and returns a largest key on this priority queue.
*
* @return a largest key on this priority queue
* @throws NoSuchElementException if this priority queue is empty
*/
public Key delMax() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
Key max = pq[1];
exch(1, n--);
sink(1);
pq[n+1] = null; // to avoid loitering and help with garbage collection
if ((n > 0) && (n == (pq.length - 1) / 4)) resize(pq.length / 2);
assert isMaxHeap();
return max;
}
/***************************************************************************
* Helper functions to restore the heap invariant.
***************************************************************************/
private void swim(int k) {
while (k > 1 && less(k/2, k)) {
exch(k/2, k);
k = k/2;
}
}
private void sink(int k) {
while (2*k <= n) {
int j = 2*k;
if (j < n && less(j, j+1)) j++;
if (!less(k, j)) break;
exch(k, j);
k = j;
}
}
/***************************************************************************
* Helper functions for compares and swaps.
***************************************************************************/
private boolean less(int i, int j) {
if (comparator == null) {
return ((Comparable<Key>) pq[i]).compareTo(pq[j]) < 0;
}
else {
return comparator.compare(pq[i], pq[j]) < 0;
}
}
private void exch(int i, int j) {
Key swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
}
// is pq[1..n] a max heap?
private boolean isMaxHeap() {
for (int i = 1; i <= n; i++) {
if (pq[i] == null) return false;
}
for (int i = n+1; i < pq.length; i++) {
if (pq[i] != null) return false;
}
if (pq[0] != null) return false;
return isMaxHeapOrdered(1);
}
// is subtree of pq[1..n] rooted at k a max heap?
private boolean isMaxHeapOrdered(int k) {
if (k > n) return true;
int left = 2*k;
int right = 2*k + 1;
if (left <= n && less(k, left)) return false;
if (right <= n && less(k, right)) return false;
return isMaxHeapOrdered(left) && isMaxHeapOrdered(right);
}
/***************************************************************************
* Iterator.
***************************************************************************/
/**
* Returns an iterator that iterates over the keys on this priority queue
* in descending order.
* The iterator doesn't implement {@code remove()} since it's optional.
*
* @return an iterator that iterates over the keys in descending order
*/
public Iterator<Key> iterator() {
return new HeapIterator();
}
private class HeapIterator implements Iterator<Key> {
// create a new pq
private MaxPQ<Key> copy;
// add all items to copy of heap
// takes linear time since already in heap order so no keys move
public HeapIterator() {
if (comparator == null) copy = new MaxPQ<Key>(size());
else copy = new MaxPQ<Key>(size(), comparator);
for (int i = 1; i <= n; i++)
copy.insert(pq[i]);
}
public boolean hasNext() { return !copy.isEmpty(); }
public void remove() { throw new UnsupportedOperationException(); }
public Key next() {
if (!hasNext()) throw new NoSuchElementException();
return copy.delMax();
}
}
/**
* Unit tests the {@code MaxPQ} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
MaxPQ<String> pq = new MaxPQ<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) pq.insert(item);
else if (!pq.isEmpty()) StdOut.print(pq.delMax() + " ");
}
StdOut.println("(" + pq.size() + " left on pq)");
}
}
|
[] |
{
"number": "2.4.15",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/24pq/MaxPQ.java",
"params": [
"< tinyPQ.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
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, initially containing
\((0^3, 0, 0), (1^3 + 1^3, 1, 1), (2^3 + 2^3, 2, 2), \ldots, (n^3 + n^3, n, n)\).
Then, while the priority queue is nonempty, remove the smallest item
\(i^3 + j^3,\; i, \; j)\), print it, and then, if
\(j < n\), insert the item \((i^3 + (j+1)^3,\; i,\; j+1)\).
Use this program to find all distinct integers \(a, b, c\), and \(d\) between 0 and
\(10^6\) such that
\(a^3 + b^3 = c^3 + d^3\), such as
\(1729 = 9^3 + 10^3 = 1^3 + 12^3\).
|
/******************************************************************************
* Compilation: javac CubeSum.java
* Execution: java CubeSum n
* Dependencies: MinPQ.java
*
* Print out integers of the form a^3 + b^3 in sorted order, where
* 0 <= a <= b <= n.
*
* % java CubeSum 12
* 0 = 0^3 + 0^3
* 1 = 0^3 + 1^3
* 2 = 1^3 + 1^3
* 8 = 0^3 + 2^3
* 9 = 1^3 + 2^3
* ...
* 1729 = 9^3 + 10^3
* 1729 = 1^3 + 12^3
* ...
* 3456 = 12^3 + 12^3
*
* Remarks
* -------
* - Easily extends to handle sums of the form f(a) + g(b)
* - Prints out a sum more than once if it can be obtained
* in more than one way, e.g., 1729 = 9^3 + 10^3 = 1^3 + 12^3
*
******************************************************************************/
public class CubeSum implements Comparable<CubeSum> {
private final int sum;
private final int i;
private final int j;
public CubeSum(int i, int j) {
this.sum = i*i*i + j*j*j;
this.i = i;
this.j = j;
}
public int compareTo(CubeSum that) {
if (this.sum < that.sum) return -1;
if (this.sum > that.sum) return +1;
return 0;
}
public String toString() {
return sum + " = " + i + "^3" + " + " + j + "^3";
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
// initialize priority queue
MinPQ<CubeSum> pq = new MinPQ<CubeSum>();
for (int i = 0; i <= n; i++) {
pq.insert(new CubeSum(i, i));
}
// find smallest sum, print it out, and update
while (!pq.isEmpty()) {
CubeSum s = pq.delMin();
StdOut.println(s);
if (s.j < n)
pq.insert(new CubeSum(s.i, s.j + 1));
}
}
}
|
[] |
{
"number": "2.4.25",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/24pq/CubeSum.java",
"params": [
"4",
"12"
],
"dependencies": [
"MinPQ.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Interval 1D data type. Write three static comparators for Interval1D.java, one that compares intervals by their left endpoing, one that compares intervals by their right endpoint, and one that compares intervals by their length.
|
/******************************************************************************
* Compilation: javac Insertion.java
* Execution: java Insertion < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt
* https://algs4.cs.princeton.edu/21elementary/words3.txt
*
* Sorts a sequence of strings from standard input using insertion sort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Insertion < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Insertion < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
import java.util.Comparator;
/**
* The {@code Insertion} class provides static methods for sorting an
* array using insertion sort.
* <p>
* In the worst case, this implementation makes ~ ½ <em>n</em><sup>2</sup>
* compares and ~ ½ <em>n</em><sup>2</sup> exchanges to sort an array
* of length <em>n</em>. So, it is not suitable for sorting large arbitrary
* arrays. More precisely, the number of exchanges is exactly equal to the
* number of inversions. So, for example, it sorts a partially-sorted array
* in linear time.
* <p>
* This sorting algorithm is stable.
* It uses Θ(1) extra memory (not including the input array).
* <p>
* See <a href="https://algs4.cs.princeton.edu/21elementary/InsertionPedantic.java.html">InsertionPedantic.java</a>
* for a version that eliminates the compiler warning.
* <p>
* For additional documentation, see <a href="https://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Insertion {
// This class should not be instantiated.
private Insertion() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
int n = a.length;
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
exch(a, j, j-1);
}
assert isSorted(a, 0, i);
}
assert isSorted(a);
}
/**
* Rearranges the subarray a[lo..hi) in ascending order, using the natural order.
* @param a the array to be sorted
* @param lo left endpoint (inclusive)
* @param hi right endpoint (exclusive)
*/
public static void sort(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i < hi; i++) {
for (int j = i; j > lo && less(a[j], a[j-1]); j--) {
exch(a, j, j-1);
}
}
assert isSorted(a, lo, hi);
}
/**
* Rearranges the array in ascending order, using a comparator.
* @param a the array
* @param comparator the comparator specifying the order
*/
public static void sort(Object[] a, Comparator comparator) {
int n = a.length;
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && less(a[j], a[j-1], comparator); j--) {
exch(a, j, j-1);
}
assert isSorted(a, 0, i, comparator);
}
assert isSorted(a, comparator);
}
/**
* Rearranges the subarray a[lo..hi) in ascending order, using a comparator.
* @param a the array
* @param lo left endpoint (inclusive)
* @param hi right endpoint (exclusive)
* @param comparator the comparator specifying the order
*/
public static void sort(Object[] a, int lo, int hi, Comparator comparator) {
for (int i = lo + 1; i < hi; i++) {
for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--) {
exch(a, j, j-1);
}
}
assert isSorted(a, lo, hi, comparator);
}
// return a permutation that gives the elements in a[] in ascending order
// do not change the original array a[]
/**
* Returns a permutation that gives the elements in the array in ascending order.
* @param a the array
* @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},
* ..., {@code a[p[n-1]]} are in ascending order
*/
public static int[] indexSort(Comparable[] a) {
int n = a.length;
int[] index = new int[n];
for (int i = 0; i < n; i++)
index[i] = i;
for (int i = 1; i < n; i++)
for (int j = i; j > 0 && less(a[index[j]], a[index[j-1]]); j--)
exch(index, j, j-1);
return index;
}
/***************************************************************************
* Helper sorting functions.
***************************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// is v < w ?
private static boolean less(Object v, Object w, Comparator comparator) {
return comparator.compare(v, w) < 0;
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// exchange a[i] and a[j] (for indirect sort)
private static void exch(int[] a, int i, int j) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length);
}
// is the array a[lo..hi) sorted
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i < hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
private static boolean isSorted(Object[] a, Comparator comparator) {
return isSorted(a, 0, a.length, comparator);
}
// is the array a[lo..hi) sorted
private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {
for (int i = lo + 1; i < hi; i++)
if (less(a[i], a[i-1], comparator)) return false;
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; insertion sorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Insertion.sort(a);
show(a);
}
}
|
[
"https://algs4.cs.princeton.edu/21elementary/words3.txt",
"https://algs4.cs.princeton.edu/21elementary/tiny.txt"
] |
{
"number": "2.5.27",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/25applications/Insertion.java",
"params": [
"< tiny.txt",
"< words3.txt"
],
"dependencies": [
"StdOut.java",
"StdIn.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Sort files by name. Write a program FileSorter.java that takes the name of a directory as a command line input and prints out all of the files in the current directory, sorted by filename. Hint: use the java.io.File data type.
|
/******************************************************************************
* Compilation: javac FileSorter.java
* Execution: java FileSorter directory-name
* Dependencies: StdOut.java
*
* Prints out all of the files in the given directory in
* sorted order.
*
* % java FileSorter .
*
******************************************************************************/
import java.io.File;
import java.util.Arrays;
public class FileSorter {
public static void main(String[] args) {
File directory = new File(args[0]); // root directory
if (!directory.exists()) {
StdOut.println(args[0] + " does not exist");
return;
}
if (!directory.isDirectory()) {
StdOut.println(args[0] + " is not a directory");
return;
}
File[] files = directory.listFiles();
if (files == null) {
StdOut.println("could not read files");
return;
}
Arrays.sort(files);
for (int i = 0; i < files.length; i++)
StdOut.println(files[i].getName());
}
}
|
[] |
{
"number": "2.5.28",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/25applications/FileSorter.java",
"params": [
"java FileSorter ."
],
"dependencies": [
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Write a client
program GPA.java that creates a symbol table mapping letter grades to numerical
scores, as in the table below, then reads from standard input a list of letter
grades and computes and prints the GPA (the average of the numerical
scores of the corresponding grades). A+ A A- B+ B B- C+ C C- D F
4.33 4.00 3.67 3.33 3.00 2.67 2.33 2.00 1.67 1.00 0.00
|
/******************************************************************************
* Compilation: javac GPA.java
* Execution: java GPA < input.txt
* Dependencies: ST.java
*
* Create a symbol table mapping letter grades to numerical
* scores, then read a list of letter grades from standard input,
* and print the GPA.
*
* % java GPA
* A- B+ B+ B-
* GPA = 3.25
*
******************************************************************************/
public class GPA {
public static void main(String[] args) {
// create symbol table of grades and values
ST<String, Double> grades = new ST<String, Double>();
grades.put("A", 4.00);
grades.put("B", 3.00);
grades.put("C", 2.00);
grades.put("D", 1.00);
grades.put("F", 0.00);
grades.put("A+", 4.33);
grades.put("B+", 3.33);
grades.put("C+", 2.33);
grades.put("A-", 3.67);
grades.put("B-", 2.67);
// read grades from standard input and compute gpa
int n = 0;
double total = 0.0;
for (n = 0; !StdIn.isEmpty(); n++) {
String grade = StdIn.readString();
double value = grades.get(grade);
total += value;
}
double gpa = total / n;
StdOut.println("GPA = " + gpa);
}
}
|
[] |
{
"number": "3.1.1",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/GPA.java",
"params": [
"<<EOF\nA- B+ B+ B-\nEOF"
],
"dependencies": [
"ST.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Develop a symbol-table implementation ArrayST.java that uses an (unordered) array as the underlying data structure to implement our basic symbol table API.
|
/******************************************************************************
* Compilation: javac ArrayST.java
* Execution: java ArrayST < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
*
* Symbol table implementation with unordered array. Uses repeated
* doubling to resize the array.
*
* % java ArrayST < tinyST.txt
* S 0
* H 5
* X 7
* R 3
* C 4
* L 11
* A 8
* M 9
* P 10
* E 12
*
******************************************************************************/
public class ArrayST<Key, Value> {
private static final int INIT_SIZE = 8;
private Value[] vals; // symbol table values
private Key[] keys; // symbol table keys
private int n = 0; // number of elements in symbol table
public ArrayST() {
keys = (Key[]) new Object[INIT_SIZE];
vals = (Value[]) new Object[INIT_SIZE];
}
// return the number of key-value pairs in the symbol table
public int size() {
return n;
}
// is the symbol table empty?
public boolean isEmpty() {
return size() == 0;
}
// resize the parallel arrays to the given capacity
private void resize(int capacity) {
Key[] tempk = (Key[]) new Object[capacity];
Value[] tempv = (Value[]) new Object[capacity];
for (int i = 0; i < n; i++)
tempk[i] = keys[i];
for (int i = 0; i < n; i++)
tempv[i] = vals[i];
keys = tempk;
vals = tempv;
}
// insert the key-value pair into the symbol table
public void put(Key key, Value val) {
// to deal with duplicates
delete(key);
// double size of arrays if necessary
if (n >= vals.length) resize(2*n);
// add new key and value at the end of array
vals[n] = val;
keys[n] = key;
n++;
}
public Value get(Key key) {
for (int i = 0; i < n; i++)
if (keys[i].equals(key)) return vals[i];
return null;
}
public Iterable<Key> keys() {
Queue<Key> queue = new Queue<Key>();
for (int i = 0; i < n; i++)
queue.enqueue(keys[i]);
return queue;
}
// remove given key (and associated value)
public void delete(Key key) {
for (int i = 0; i < n; i++) {
if (key.equals(keys[i])) {
keys[i] = keys[n-1];
vals[i] = vals[n-1];
keys[n-1] = null;
vals[n-1] = null;
n--;
if (n > 0 && n == keys.length/4) resize(keys.length/2);
return;
}
}
}
/***************************************************************************
* Test routine.
***************************************************************************/
public static void main(String[] args) {
ArrayST<String, Integer> st = new ArrayST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
}
|
[
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] |
{
"number": "3.1.2",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/ArrayST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Implement size(), delete(), and keys() for SequentialSearchST.java.
|
/******************************************************************************
* Compilation: javac SequentialSearchST.java
* Execution: java SequentialSearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with sequential search in an
* unordered linked list of key-value pairs.
*
* % more tinyST.txt
* S E A R C H E X A M P L E
*
* % java SequentialSearchST < tinyST.txt
* L 11
* P 10
* M 9
* X 7
* H 5
* C 4
* R 3
* A 8
* E 12
* S 0
*
******************************************************************************/
/**
* The {@code SequentialSearchST} class represents an (unordered)
* symbol table of generic key-value pairs.
* It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>,
* <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods.
* It also provides a <em>keys</em> method for iterating over all of the keys.
* A symbol table implements the <em>associative array</em> abstraction:
* when associating a value with a key that is already in the symbol table,
* the convention is to replace the old value with the new value.
* The class also uses the convention that values cannot be {@code null}. Setting the
* value associated with a key to {@code null} is equivalent to deleting the key
* from the symbol table.
* <p>
* It relies on the {@code equals()} method to test whether two keys
* are equal. It does not call either the {@code compareTo()} or
* {@code hashCode()} method.
* <p>
* This implementation uses a <em>singly linked list</em> and
* <em>sequential search</em>.
* The <em>put</em> and <em>delete</em> operations take Θ(<em>n</em>).
* The <em>get</em> and <em>contains</em> operations takes Θ(<em>n</em>)
* time in the worst case.
* The <em>size</em>, and <em>is-empty</em> operations take Θ(1) time.
* Construction takes Θ(1) time.
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class SequentialSearchST<Key, Value> {
private int n; // number of key-value pairs
private Node first; // the linked list of key-value pairs
// a helper linked list data type
private class Node {
private Key key;
private Value val;
private Node next;
public Node(Key key, Value val, Node next) {
this.key = key;
this.val = val;
this.next = next;
}
}
/**
* Initializes an empty symbol table.
*/
public SequentialSearchST() {
}
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return n;
}
/**
* Returns true if this symbol table is empty.
*
* @return {@code true} if this symbol table is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns true if this symbol table contains the specified key.
*
* @param key the key
* @return {@code true} if this symbol table contains {@code key};
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
if (key == null) throw new IllegalArgumentException("argument to contains() is null");
return get(key) != null;
}
/**
* Returns the value associated with the given key in this symbol table.
*
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key))
return x.val;
}
return null;
}
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key)) {
x.val = val;
return;
}
}
first = new Node(key, val, first);
n++;
}
/**
* Removes the specified key and its associated value from this symbol table
* (if the key is in this symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
first = delete(first, key);
}
// delete key in linked list beginning at Node x
// warning: function call stack too large if table is large
private Node delete(Node x, Key key) {
if (x == null) return null;
if (key.equals(x.key)) {
n--;
return x.next;
}
x.next = delete(x.next, key);
return x;
}
/**
* Returns all keys in the symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in the symbol table
*/
public Iterable<Key> keys() {
Queue<Key> queue = new Queue<Key>();
for (Node x = first; x != null; x = x.next)
queue.enqueue(x.key);
return queue;
}
/**
* Unit tests the {@code SequentialSearchST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
SequentialSearchST<String, Integer> st = new SequentialSearchST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
}
|
[
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] |
{
"number": "3.1.5",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/SequentialSearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Implement the delete() method for BinarySearchST.java.
|
/******************************************************************************
* Compilation: javac BinarySearchST.java
* Execution: java BinarySearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with binary search in an ordered array.
*
* % more tinyST.txt
* S E A R C H E X A M P L E
*
* % java BinarySearchST < tinyST.txt
* A 8
* C 4
* E 12
* H 5
* L 11
* M 9
* P 10
* R 3
* S 0
* X 7
*
******************************************************************************/
import java.util.NoSuchElementException;
/**
* The {@code BST} class represents an ordered symbol table of generic
* key-value pairs.
* It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>,
* <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods.
* It also provides ordered methods for finding the <em>minimum</em>,
* <em>maximum</em>, <em>floor</em>, <em>select</em>, and <em>ceiling</em>.
* It also provides a <em>keys</em> method for iterating over all of the keys.
* A symbol table implements the <em>associative array</em> abstraction:
* when associating a value with a key that is already in the symbol table,
* the convention is to replace the old value with the new value.
* Unlike {@link java.util.Map}, this class uses the convention that
* values cannot be {@code null}—setting the
* value associated with a key to {@code null} is equivalent to deleting the key
* from the symbol table.
* <p>
* It requires that
* the key type implements the {@code Comparable} interface and calls the
* {@code compareTo()} and method to compare two keys. It does not call either
* {@code equals()} or {@code hashCode()}.
* <p>
* This implementation uses a <em>sorted array</em>.
* The <em>put</em> and <em>remove</em> operations take Θ(<em>n</em>)
* time in the worst case.
* The <em>contains</em>, <em>ceiling</em>, <em>floor</em>,
* and <em>rank</em> operations take Θ(log <em>n</em>) time in the worst
* case.
* The <em>size</em>, <em>is-empty</em>, <em>minimum</em>, <em>maximum</em>,
* and <em>select</em> operations take Θ(1) time.
* Construction takes Θ(1) time.
* <p>
* For alternative implementations of the symbol table API,
* see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},
* {@link SeparateChainingHashST}, and {@link LinearProbingHashST},
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class BinarySearchST<Key extends Comparable<Key>, Value> {
private static final int INIT_CAPACITY = 2;
private Key[] keys;
private Value[] vals;
private int n = 0;
/**
* Initializes an empty symbol table.
*/
public BinarySearchST() {
this(INIT_CAPACITY);
}
/**
* Initializes an empty symbol table with the specified initial capacity.
* @param capacity the maximum capacity
*/
public BinarySearchST(int capacity) {
keys = (Key[]) new Comparable[capacity];
vals = (Value[]) new Object[capacity];
}
// resize the underlying arrays
private void resize(int capacity) {
assert capacity >= n;
Key[] tempk = (Key[]) new Comparable[capacity];
Value[] tempv = (Value[]) new Object[capacity];
for (int i = 0; i < n; i++) {
tempk[i] = keys[i];
tempv[i] = vals[i];
}
vals = tempv;
keys = tempk;
}
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return n;
}
/**
* Returns true if this symbol table is empty.
*
* @return {@code true} if this symbol table is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Does this symbol table contain the given key?
*
* @param key the key
* @return {@code true} if this symbol table contains {@code key} and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
if (key == null) throw new IllegalArgumentException("argument to contains() is null");
return get(key) != null;
}
/**
* Returns the value associated with the given key in this symbol table.
*
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
if (isEmpty()) return null;
int i = rank(key);
if (i < n && keys[i].compareTo(key) == 0) return vals[i];
return null;
}
/**
* Returns the number of keys in this symbol table strictly less than {@code key}.
*
* @param key the key
* @return the number of keys in the symbol table strictly less than {@code key}
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException("argument to rank() is null");
int lo = 0, hi = n-1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int cmp = key.compareTo(keys[mid]);
if (cmp < 0) hi = mid - 1;
else if (cmp > 0) lo = mid + 1;
else return mid;
}
return lo;
}
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
int i = rank(key);
// key is already in table
if (i < n && keys[i].compareTo(key) == 0) {
vals[i] = val;
return;
}
// insert new key-value pair
if (n == keys.length) resize(2*keys.length);
for (int j = n; j > i; j--) {
keys[j] = keys[j-1];
vals[j] = vals[j-1];
}
keys[i] = key;
vals[i] = val;
n++;
assert check();
}
/**
* Removes the specified key and associated value from this symbol table
* (if the key is in the symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
if (isEmpty()) return;
// compute rank
int i = rank(key);
// key not in table
if (i == n || keys[i].compareTo(key) != 0) {
return;
}
for (int j = i; j < n-1; j++) {
keys[j] = keys[j+1];
vals[j] = vals[j+1];
}
n--;
keys[n] = null; // to avoid loitering
vals[n] = null;
// resize if 1/4 full
if (n > 0 && n == keys.length/4) resize(keys.length/2);
assert check();
}
/**
* Removes the smallest key and associated value from this symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMin() {
if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error");
delete(min());
}
/**
* Removes the largest key and associated value from this symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error");
delete(max());
}
/***************************************************************************
* Ordered symbol table methods.
***************************************************************************/
/**
* Returns the smallest key in this symbol table.
*
* @return the smallest key in this symbol table
* @throws NoSuchElementException if this symbol table is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return keys[0];
}
/**
* Returns the largest key in this symbol table.
*
* @return the largest key in this symbol table
* @throws NoSuchElementException if this symbol table is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return keys[n-1];
}
/**
* Return the kth smallest key in this symbol table.
*
* @param k the order statistic
* @return the {@code k}th smallest key in this symbol table
* @throws IllegalArgumentException unless {@code k} is between 0 and
* <em>n</em>–1
*/
public Key select(int k) {
if (k < 0 || k >= size()) {
throw new IllegalArgumentException("called select() with invalid argument: " + k);
}
return keys[k];
}
/**
* Returns the largest key in this symbol table less than or equal to {@code key}.
*
* @param key the key
* @return the largest key in this symbol table less than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key floor(Key key) {
if (key == null) throw new IllegalArgumentException("argument to floor() is null");
int i = rank(key);
if (i < n && key.compareTo(keys[i]) == 0) return keys[i];
if (i == 0) throw new NoSuchElementException("argument to floor() is too small");
else return keys[i-1];
}
/**
* Returns the smallest key in this symbol table greater than or equal to {@code key}.
*
* @param key the key
* @return the smallest key in this symbol table greater than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key ceiling(Key key) {
if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
int i = rank(key);
if (i == n) throw new NoSuchElementException("argument to ceiling() is too large");
else return keys[i];
}
/**
* Returns the number of keys in this symbol table in the specified range.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return the number of keys in this symbol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public int size(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
if (hi == null) throw new IllegalArgumentException("second argument to size() is null");
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
/**
* Returns all keys in this symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in this symbol table
*/
public Iterable<Key> keys() {
return keys(min(), max());
}
/**
* Returns all keys in this symbol table in the given range,
* as an {@code Iterable}.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return all keys in this symbol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public Iterable<Key> keys(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");
Queue<Key> queue = new Queue<Key>();
if (lo.compareTo(hi) > 0) return queue;
for (int i = rank(lo); i < rank(hi); i++)
queue.enqueue(keys[i]);
if (contains(hi)) queue.enqueue(keys[rank(hi)]);
return queue;
}
/***************************************************************************
* Check internal invariants.
***************************************************************************/
private boolean check() {
return isSorted() && rankCheck();
}
// are the items in the array in ascending order?
private boolean isSorted() {
for (int i = 1; i < size(); i++)
if (keys[i].compareTo(keys[i-1]) < 0) return false;
return true;
}
// check that rank(select(i)) = i
private boolean rankCheck() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (int i = 0; i < size(); i++)
if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;
return true;
}
/**
* Unit tests the {@code BinarySearchST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
}
|
[
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] |
{
"number": "3.1.16",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Implement the floor() method for BinarySearchST.java .
|
/******************************************************************************
* Compilation: javac BinarySearchST.java
* Execution: java BinarySearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with binary search in an ordered array.
*
* % more tinyST.txt
* S E A R C H E X A M P L E
*
* % java BinarySearchST < tinyST.txt
* A 8
* C 4
* E 12
* H 5
* L 11
* M 9
* P 10
* R 3
* S 0
* X 7
*
******************************************************************************/
import java.util.NoSuchElementException;
/**
* The {@code BST} class represents an ordered symbol table of generic
* key-value pairs.
* It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>,
* <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods.
* It also provides ordered methods for finding the <em>minimum</em>,
* <em>maximum</em>, <em>floor</em>, <em>select</em>, and <em>ceiling</em>.
* It also provides a <em>keys</em> method for iterating over all of the keys.
* A symbol table implements the <em>associative array</em> abstraction:
* when associating a value with a key that is already in the symbol table,
* the convention is to replace the old value with the new value.
* Unlike {@link java.util.Map}, this class uses the convention that
* values cannot be {@code null}—setting the
* value associated with a key to {@code null} is equivalent to deleting the key
* from the symbol table.
* <p>
* It requires that
* the key type implements the {@code Comparable} interface and calls the
* {@code compareTo()} and method to compare two keys. It does not call either
* {@code equals()} or {@code hashCode()}.
* <p>
* This implementation uses a <em>sorted array</em>.
* The <em>put</em> and <em>remove</em> operations take Θ(<em>n</em>)
* time in the worst case.
* The <em>contains</em>, <em>ceiling</em>, <em>floor</em>,
* and <em>rank</em> operations take Θ(log <em>n</em>) time in the worst
* case.
* The <em>size</em>, <em>is-empty</em>, <em>minimum</em>, <em>maximum</em>,
* and <em>select</em> operations take Θ(1) time.
* Construction takes Θ(1) time.
* <p>
* For alternative implementations of the symbol table API,
* see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},
* {@link SeparateChainingHashST}, and {@link LinearProbingHashST},
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class BinarySearchST<Key extends Comparable<Key>, Value> {
private static final int INIT_CAPACITY = 2;
private Key[] keys;
private Value[] vals;
private int n = 0;
/**
* Initializes an empty symbol table.
*/
public BinarySearchST() {
this(INIT_CAPACITY);
}
/**
* Initializes an empty symbol table with the specified initial capacity.
* @param capacity the maximum capacity
*/
public BinarySearchST(int capacity) {
keys = (Key[]) new Comparable[capacity];
vals = (Value[]) new Object[capacity];
}
// resize the underlying arrays
private void resize(int capacity) {
assert capacity >= n;
Key[] tempk = (Key[]) new Comparable[capacity];
Value[] tempv = (Value[]) new Object[capacity];
for (int i = 0; i < n; i++) {
tempk[i] = keys[i];
tempv[i] = vals[i];
}
vals = tempv;
keys = tempk;
}
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return n;
}
/**
* Returns true if this symbol table is empty.
*
* @return {@code true} if this symbol table is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Does this symbol table contain the given key?
*
* @param key the key
* @return {@code true} if this symbol table contains {@code key} and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
if (key == null) throw new IllegalArgumentException("argument to contains() is null");
return get(key) != null;
}
/**
* Returns the value associated with the given key in this symbol table.
*
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
if (isEmpty()) return null;
int i = rank(key);
if (i < n && keys[i].compareTo(key) == 0) return vals[i];
return null;
}
/**
* Returns the number of keys in this symbol table strictly less than {@code key}.
*
* @param key the key
* @return the number of keys in the symbol table strictly less than {@code key}
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException("argument to rank() is null");
int lo = 0, hi = n-1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int cmp = key.compareTo(keys[mid]);
if (cmp < 0) hi = mid - 1;
else if (cmp > 0) lo = mid + 1;
else return mid;
}
return lo;
}
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
int i = rank(key);
// key is already in table
if (i < n && keys[i].compareTo(key) == 0) {
vals[i] = val;
return;
}
// insert new key-value pair
if (n == keys.length) resize(2*keys.length);
for (int j = n; j > i; j--) {
keys[j] = keys[j-1];
vals[j] = vals[j-1];
}
keys[i] = key;
vals[i] = val;
n++;
assert check();
}
/**
* Removes the specified key and associated value from this symbol table
* (if the key is in the symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
if (isEmpty()) return;
// compute rank
int i = rank(key);
// key not in table
if (i == n || keys[i].compareTo(key) != 0) {
return;
}
for (int j = i; j < n-1; j++) {
keys[j] = keys[j+1];
vals[j] = vals[j+1];
}
n--;
keys[n] = null; // to avoid loitering
vals[n] = null;
// resize if 1/4 full
if (n > 0 && n == keys.length/4) resize(keys.length/2);
assert check();
}
/**
* Removes the smallest key and associated value from this symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMin() {
if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error");
delete(min());
}
/**
* Removes the largest key and associated value from this symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error");
delete(max());
}
/***************************************************************************
* Ordered symbol table methods.
***************************************************************************/
/**
* Returns the smallest key in this symbol table.
*
* @return the smallest key in this symbol table
* @throws NoSuchElementException if this symbol table is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return keys[0];
}
/**
* Returns the largest key in this symbol table.
*
* @return the largest key in this symbol table
* @throws NoSuchElementException if this symbol table is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return keys[n-1];
}
/**
* Return the kth smallest key in this symbol table.
*
* @param k the order statistic
* @return the {@code k}th smallest key in this symbol table
* @throws IllegalArgumentException unless {@code k} is between 0 and
* <em>n</em>–1
*/
public Key select(int k) {
if (k < 0 || k >= size()) {
throw new IllegalArgumentException("called select() with invalid argument: " + k);
}
return keys[k];
}
/**
* Returns the largest key in this symbol table less than or equal to {@code key}.
*
* @param key the key
* @return the largest key in this symbol table less than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key floor(Key key) {
if (key == null) throw new IllegalArgumentException("argument to floor() is null");
int i = rank(key);
if (i < n && key.compareTo(keys[i]) == 0) return keys[i];
if (i == 0) throw new NoSuchElementException("argument to floor() is too small");
else return keys[i-1];
}
/**
* Returns the smallest key in this symbol table greater than or equal to {@code key}.
*
* @param key the key
* @return the smallest key in this symbol table greater than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key ceiling(Key key) {
if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
int i = rank(key);
if (i == n) throw new NoSuchElementException("argument to ceiling() is too large");
else return keys[i];
}
/**
* Returns the number of keys in this symbol table in the specified range.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return the number of keys in this symbol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public int size(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
if (hi == null) throw new IllegalArgumentException("second argument to size() is null");
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
/**
* Returns all keys in this symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in this symbol table
*/
public Iterable<Key> keys() {
return keys(min(), max());
}
/**
* Returns all keys in this symbol table in the given range,
* as an {@code Iterable}.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return all keys in this symbol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public Iterable<Key> keys(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");
Queue<Key> queue = new Queue<Key>();
if (lo.compareTo(hi) > 0) return queue;
for (int i = rank(lo); i < rank(hi); i++)
queue.enqueue(keys[i]);
if (contains(hi)) queue.enqueue(keys[rank(hi)]);
return queue;
}
/***************************************************************************
* Check internal invariants.
***************************************************************************/
private boolean check() {
return isSorted() && rankCheck();
}
// are the items in the array in ascending order?
private boolean isSorted() {
for (int i = 1; i < size(); i++)
if (keys[i].compareTo(keys[i-1]) < 0) return false;
return true;
}
// check that rank(select(i)) = i
private boolean rankCheck() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (int i = 0; i < size(); i++)
if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;
return true;
}
/**
* Unit tests the {@code BinarySearchST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
}
|
[
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] |
{
"number": "3.1.17",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
Certification. Add assert statements to BinarySearchST.java to check algorithm invariants and data structure integrity after every
insertion and deletion. For example, every index i should always be equal to rank(select(i)) and the array should
always be in order.
|
/******************************************************************************
* Compilation: javac BinarySearchST.java
* Execution: java BinarySearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with binary search in an ordered array.
*
* % more tinyST.txt
* S E A R C H E X A M P L E
*
* % java BinarySearchST < tinyST.txt
* A 8
* C 4
* E 12
* H 5
* L 11
* M 9
* P 10
* R 3
* S 0
* X 7
*
******************************************************************************/
import java.util.NoSuchElementException;
/**
* The {@code BST} class represents an ordered symbol table of generic
* key-value pairs.
* It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>,
* <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods.
* It also provides ordered methods for finding the <em>minimum</em>,
* <em>maximum</em>, <em>floor</em>, <em>select</em>, and <em>ceiling</em>.
* It also provides a <em>keys</em> method for iterating over all of the keys.
* A symbol table implements the <em>associative array</em> abstraction:
* when associating a value with a key that is already in the symbol table,
* the convention is to replace the old value with the new value.
* Unlike {@link java.util.Map}, this class uses the convention that
* values cannot be {@code null}—setting the
* value associated with a key to {@code null} is equivalent to deleting the key
* from the symbol table.
* <p>
* It requires that
* the key type implements the {@code Comparable} interface and calls the
* {@code compareTo()} and method to compare two keys. It does not call either
* {@code equals()} or {@code hashCode()}.
* <p>
* This implementation uses a <em>sorted array</em>.
* The <em>put</em> and <em>remove</em> operations take Θ(<em>n</em>)
* time in the worst case.
* The <em>contains</em>, <em>ceiling</em>, <em>floor</em>,
* and <em>rank</em> operations take Θ(log <em>n</em>) time in the worst
* case.
* The <em>size</em>, <em>is-empty</em>, <em>minimum</em>, <em>maximum</em>,
* and <em>select</em> operations take Θ(1) time.
* Construction takes Θ(1) time.
* <p>
* For alternative implementations of the symbol table API,
* see {@link ST}, {@link BST}, {@link SequentialSearchST}, {@link RedBlackBST},
* {@link SeparateChainingHashST}, and {@link LinearProbingHashST},
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*/
public class BinarySearchST<Key extends Comparable<Key>, Value> {
private static final int INIT_CAPACITY = 2;
private Key[] keys;
private Value[] vals;
private int n = 0;
/**
* Initializes an empty symbol table.
*/
public BinarySearchST() {
this(INIT_CAPACITY);
}
/**
* Initializes an empty symbol table with the specified initial capacity.
* @param capacity the maximum capacity
*/
public BinarySearchST(int capacity) {
keys = (Key[]) new Comparable[capacity];
vals = (Value[]) new Object[capacity];
}
// resize the underlying arrays
private void resize(int capacity) {
assert capacity >= n;
Key[] tempk = (Key[]) new Comparable[capacity];
Value[] tempv = (Value[]) new Object[capacity];
for (int i = 0; i < n; i++) {
tempk[i] = keys[i];
tempv[i] = vals[i];
}
vals = tempv;
keys = tempk;
}
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return n;
}
/**
* Returns true if this symbol table is empty.
*
* @return {@code true} if this symbol table is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Does this symbol table contain the given key?
*
* @param key the key
* @return {@code true} if this symbol table contains {@code key} and
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
if (key == null) throw new IllegalArgumentException("argument to contains() is null");
return get(key) != null;
}
/**
* Returns the value associated with the given key in this symbol table.
*
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
if (isEmpty()) return null;
int i = rank(key);
if (i < n && keys[i].compareTo(key) == 0) return vals[i];
return null;
}
/**
* Returns the number of keys in this symbol table strictly less than {@code key}.
*
* @param key the key
* @return the number of keys in the symbol table strictly less than {@code key}
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public int rank(Key key) {
if (key == null) throw new IllegalArgumentException("argument to rank() is null");
int lo = 0, hi = n-1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int cmp = key.compareTo(keys[mid]);
if (cmp < 0) hi = mid - 1;
else if (cmp > 0) lo = mid + 1;
else return mid;
}
return lo;
}
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
int i = rank(key);
// key is already in table
if (i < n && keys[i].compareTo(key) == 0) {
vals[i] = val;
return;
}
// insert new key-value pair
if (n == keys.length) resize(2*keys.length);
for (int j = n; j > i; j--) {
keys[j] = keys[j-1];
vals[j] = vals[j-1];
}
keys[i] = key;
vals[i] = val;
n++;
assert check();
}
/**
* Removes the specified key and associated value from this symbol table
* (if the key is in the symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
if (isEmpty()) return;
// compute rank
int i = rank(key);
// key not in table
if (i == n || keys[i].compareTo(key) != 0) {
return;
}
for (int j = i; j < n-1; j++) {
keys[j] = keys[j+1];
vals[j] = vals[j+1];
}
n--;
keys[n] = null; // to avoid loitering
vals[n] = null;
// resize if 1/4 full
if (n > 0 && n == keys.length/4) resize(keys.length/2);
assert check();
}
/**
* Removes the smallest key and associated value from this symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMin() {
if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error");
delete(min());
}
/**
* Removes the largest key and associated value from this symbol table.
*
* @throws NoSuchElementException if the symbol table is empty
*/
public void deleteMax() {
if (isEmpty()) throw new NoSuchElementException("Symbol table underflow error");
delete(max());
}
/***************************************************************************
* Ordered symbol table methods.
***************************************************************************/
/**
* Returns the smallest key in this symbol table.
*
* @return the smallest key in this symbol table
* @throws NoSuchElementException if this symbol table is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
return keys[0];
}
/**
* Returns the largest key in this symbol table.
*
* @return the largest key in this symbol table
* @throws NoSuchElementException if this symbol table is empty
*/
public Key max() {
if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
return keys[n-1];
}
/**
* Return the kth smallest key in this symbol table.
*
* @param k the order statistic
* @return the {@code k}th smallest key in this symbol table
* @throws IllegalArgumentException unless {@code k} is between 0 and
* <em>n</em>–1
*/
public Key select(int k) {
if (k < 0 || k >= size()) {
throw new IllegalArgumentException("called select() with invalid argument: " + k);
}
return keys[k];
}
/**
* Returns the largest key in this symbol table less than or equal to {@code key}.
*
* @param key the key
* @return the largest key in this symbol table less than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key floor(Key key) {
if (key == null) throw new IllegalArgumentException("argument to floor() is null");
int i = rank(key);
if (i < n && key.compareTo(keys[i]) == 0) return keys[i];
if (i == 0) throw new NoSuchElementException("argument to floor() is too small");
else return keys[i-1];
}
/**
* Returns the smallest key in this symbol table greater than or equal to {@code key}.
*
* @param key the key
* @return the smallest key in this symbol table greater than or equal to {@code key}
* @throws NoSuchElementException if there is no such key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Key ceiling(Key key) {
if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
int i = rank(key);
if (i == n) throw new NoSuchElementException("argument to ceiling() is too large");
else return keys[i];
}
/**
* Returns the number of keys in this symbol table in the specified range.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return the number of keys in this symbol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public int size(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
if (hi == null) throw new IllegalArgumentException("second argument to size() is null");
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
/**
* Returns all keys in this symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in this symbol table
*/
public Iterable<Key> keys() {
return keys(min(), max());
}
/**
* Returns all keys in this symbol table in the given range,
* as an {@code Iterable}.
*
* @param lo minimum endpoint
* @param hi maximum endpoint
* @return all keys in this symbol table between {@code lo}
* (inclusive) and {@code hi} (inclusive)
* @throws IllegalArgumentException if either {@code lo} or {@code hi}
* is {@code null}
*/
public Iterable<Key> keys(Key lo, Key hi) {
if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");
Queue<Key> queue = new Queue<Key>();
if (lo.compareTo(hi) > 0) return queue;
for (int i = rank(lo); i < rank(hi); i++)
queue.enqueue(keys[i]);
if (contains(hi)) queue.enqueue(keys[rank(hi)]);
return queue;
}
/***************************************************************************
* Check internal invariants.
***************************************************************************/
private boolean check() {
return isSorted() && rankCheck();
}
// are the items in the array in ascending order?
private boolean isSorted() {
for (int i = 1; i < size(); i++)
if (keys[i].compareTo(keys[i-1]) < 0) return false;
return true;
}
// check that rank(select(i)) = i
private boolean rankCheck() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (int i = 0; i < size(); i++)
if (keys[i].compareTo(select(rank(keys[i]))) != 0) return false;
return true;
}
/**
* Unit tests the {@code BinarySearchST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
}
|
[
"https://algs4.cs.princeton.edu/31elementary/tinyST.txt"
] |
{
"number": "3.1.30",
"code_execution": true,
"url": "https://algs4.cs.princeton.edu/31elementary/BinarySearchST.java",
"params": [
"< tinyST.txt"
],
"dependencies": [
"StdIn.java",
"StdOut.java"
],
"chapter": null,
"chapter_title": null,
"section": null,
"section_title": null,
"type": null
}
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 15