Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Algorithms (2006)

.pdf
Скачиваний:
255
Добавлен:
17.08.2013
Размер:
9.67 Mб
Скачать

Appendix D

super.setUp();

for (int i = 1; i < TEST_SIZE; ++i) { _sortedArrayList.add(new Integer(i));

}

for (int i = TEST_SIZE; i > 0; --i) { _reverseArrayList.add(new Integer(i));

}

for (int i = 1; i < TEST_SIZE; ++i) {

_randomArrayList.add(new Integer((int)(TEST_SIZE * Math.random())));

}

}

public void testWorstCaseQuicksort() {

List list = new CallCountingList(_reverseArrayList); new QuicksortListSorter(_comparator).sort(list); reportCalls(list);

}

public void testWorstCaseShellSort() {

List list = new CallCountingList(_reverseArrayList); new ShellsortListSorter(_comparator).sort(list); reportCalls(list);

}

public void testBestCaseQuicksort() {

List list = new CallCountingList(_sortedArrayList); new QuicksortListSorter(_comparator).sort(list); reportCalls(list);

}

public void testBestCaseShellSort() {

List list = new CallCountingList(_sortedArrayList); new ShellsortListSorter(_comparator).sort(list); reportCalls(list);

}

public void testAverageCaseQuicksort() {

List list = new CallCountingList(_randomArrayList); new QuicksortListSorter(_comparator).sort(list); reportCalls(list);

}

public void testAverageCaseShellSort() {

List list = new CallCountingList(_randomArrayList); new ShellsortListSorter(_comparator).sort(list); reportCalls(list);

}

private void reportCalls(List list) { System.out.println(getName() + “: “ + list);

}

514

Answers to Exercises

}

public class CallCountingList implements List { private final List _list;

private int _insertCount; private int _addCount; private int _deleteCount; private int _getCount; private int _setCount;

public CallCountingList(List list) {

assert list != null : “list can’t be null”; _list = list;

}

public void insert(int index, Object value) throws IndexOutOfBoundsException { _list.insert(index, value);

++_insertCount;

}

public void add(Object value) { _list.add(value); ++_addCount;

}

public Object delete(int index) throws IndexOutOfBoundsException { ++_deleteCount;

return _list.delete(index);

}

public Object delete(Object value) { ++_deleteCount;

return _list.delete(value);

}

public Object get(int index) throws IndexOutOfBoundsException { ++_getCount;

return _list.get(index);

}

public Object set(int index, Object value) throws IndexOutOfBoundsException { ++_setCount;

return _list.set(index, value);

}

public void clear() { _list.clear();

}

public int indexOf(Object value) { return _list.indexOf(value);

}

public boolean contains(Object value) {

515

Appendix D

return _list.contains(value);

}

public boolean isEmpty() { return _list.isEmpty();

}

public Iterator iterator() { return _list.iterator();

}

public int size() {

return _list.size();

}

public String toString() {

return new StringBuffer(“Call-counting List: “)

.append(“add: “ + _addCount)

.append(“ insert: “ + _insertCount)

.append(“ delete: “ + _deleteCount)

.append(“ set: “ + _setCount)

.append(“ get: “ + _getCount).toString();

}

}

Exercise 4 Solution

public class InPlaceInsertionSortListSorter implements ListSorter { private final Comparator _comparator;

public InPlaceInsertionSortListSorter(Comparator comparator) { assert comparator != null : “comparator cannot be null”; _comparator = comparator;

}

public List sort(List list) {

assert list != null : “list cannot be null”;

for (int i = 1; i < list.size(); ++i) { Object value = list.get(i);

int j;

for (j = i; j > 0; --j) {

Object previousValue = list.get(j - 1);

if (_comparator.compare(value, previousValue) >= 0) { break;

}

list.set(j, previousValue);

}

list.set(j, value);

}

return list;

}

}

516

Answers to Exercises

Exercise 5 Solution

public class HybridQuicksortListSorter implements ListSorter { private final Comparator _comparator;

public HybridQuicksortListSorter(Comparator comparator) { assert comparator != null : “comparator cannot be null”; _comparator = comparator;

}

public List sort(List list) {

assert list != null : “list cannot be null”;

quicksort(list, 0, list.size() - 1);

return list;

}

private void quicksort(List list, int startIndex, int endIndex) { if (startIndex < 0 || endIndex >= list.size()) {

return;

}

if (endIndex <= startIndex) { return;

}

if (endIndex - startIndex < 5) { doInsertionSort(list, startIndex, endIndex);

} else {

doQuicksort(list, startIndex, endIndex);

}

}

private void doInsertionSort(List list, int startIndex, int endIndex) { for (int i = startIndex + 1; i <= endIndex; ++i) {

Object value = list.get(i); int j;

for (j = i; j > startIndex; --j) {

Object previousValue = list.get(j - 1);

if (_comparator.compare(value, previousValue) >= 0) { break;

}

list.set(j, previousValue);

}

list.set(j, value);

}

}

private void doQuicksort(List list, int startIndex, int endIndex) { Object value = list.get(endIndex);

int partition = partition(list, value, startIndex, endIndex - 1); if (_comparator.compare(list.get(partition), value) < 0) {

++partition;

517

Appendix D

}

swap(list, partition, endIndex);

quicksort(list, startIndex, partition - 1); quicksort(list, partition + 1, endIndex);

}

private int partition(List list, Object value, int leftIndex, int rightIndex) { int left = leftIndex;

int right = rightIndex;

while (left < right) {

if (_comparator.compare(list.get(left), value) < 0) { ++left;

continue;

}

if (_comparator.compare(list.get(right), value) >= 0) { --right;

continue;

}

swap(list, left, right); ++left;

}

return left;

}

private void swap(List list, int left, int right) { if (left == right) {

return;

}

Object temp = list.get(left); list.set(left, list.get(right)); list.set(right, temp);

}

}

Chapter 8

Exercises

1.Use a priority queue to implement a Stack.

2.Use a priority queue to implement a FIFO Queue.

3.Use a priority queue to implement a ListSorter.

4.Write a priority queue that provides access to the smallest item, rather than the largest.

518

Answers to Exercises

Exercise 1 Solution

package com.wrox.algorithms.stacks;

import com.wrox.algorithms.queues.EmptyQueueException;

import com.wrox.algorithms.queues.HeapOrderedListPriorityQueue; import com.wrox.algorithms.sorting.Comparator;

public class PriorityQueueStack extends HeapOrderedListPriorityQueue implements Stack {

private final static Comparator COMPARATOR = new StackItemComparator(); private long _count = 0;

public PriorityQueueStack() { super(COMPARATOR);

}

public void enqueue(Object value) { super.enqueue(new StackItem(++_count, value));

}

public Object dequeue() throws EmptyQueueException { return ((StackItem) super.dequeue()).getValue();

}

public void push(Object value) { enqueue(value);

}

public Object pop() throws EmptyStackException { try {

return dequeue();

} catch (EmptyQueueException e) { throw new EmptyStackException();

}

}

public Object peek() throws EmptyStackException { Object result = pop();

push(result); return result;

}

private static final class StackItem { private final long _key;

private final Object _value;

public StackItem(long key, Object value) { _key = key;

_value = value;

}

public long getKey() { return _key;

}

public Object getValue() {

519

Appendix D

return _value;

}

}

private static final class StackItemComparator implements Comparator { public int compare(Object left, Object right) throws ClassCastException {

StackItem si1 = (StackItem) left; StackItem si2 = (StackItem) right;

return (int) (si1.getKey() - si2.getKey());

}

}

}

Exercise 2 Solution

package com.wrox.algorithms.queues;

import com.wrox.algorithms.sorting.Comparator;

public class PriorityQueueFifoQueue extends HeapOrderedListPriorityQueue { private static final Comparator COMPARATOR = new QueueItemComparator(); private long _count = Long.MAX_VALUE;

public PriorityQueueFifoQueue() { super(COMPARATOR);

}

public void enqueue(Object value) { super.enqueue(new QueueItem(--_count, value));

}

public Object dequeue() throws EmptyQueueException { return ((QueueItem) super.dequeue()).getValue();

}

private static final class QueueItem { private final long _key;

private final Object _value;

public QueueItem(long key, Object value) { _key = key;

_value = value;

}

public long getKey() { return _key;

}

public Object getValue() { return _value;

520

Answers to Exercises

}

}

private static final class QueueItemComparator implements Comparator { public int compare(Object left, Object right) throws ClassCastException {

QueueItem si1 = (QueueItem) left;

QueueItem si2 = (QueueItem) right;

return (int) (si1.getKey() - si2.getKey());

}

}

}

Exercise 3 Solution

public class PriorityQueueListSorter implements ListSorter { private final Comparator _comparator;

public PriorityQueueListSorter(Comparator comparator) { assert comparator != null : “comparator cannot be null”; _comparator = comparator;

}

public List sort(List list) {

assert list != null : “list cannot be null”;

Queue queue = createPriorityQueue(list);

List result = new ArrayList(list.size());

while (!queue.isEmpty()) { result.add(queue.dequeue());

}

return result;

}

private Queue createPriorityQueue(List list) {

Comparator comparator = new ReverseComparator(_comparator); Queue queue = new HeapOrderedListPriorityQueue(comparator);

Iterator i = list.iterator(); i.first();

while (!i.isDone()) { queue.enqueue(i.current()); i.next();

}

return queue;

}

}

521

Appendix D

Exercise 4 Solution

public class MinimumOrientedHeapOrderedListPriorityQueue extends HeapOrderedListPriorityQueue {

public MinimumOrientedHeapOrderedListPriorityQueue(Comparator comparator) {

super(new ReverseComparator(comparator));

}

}

Chapter 10

Exercises

1.Write a recursive form of minimum().

2.Write a recursive form of search().

3.Write a method that takes a root node and recursively prints all the values of the tree in order.

4.Write a method that takes a root node and iteratively prints all the values of the tree in order.

5.Write a method that takes a root node and recursively prints all the values of the tree pre-order.

6.Write a method that takes a root node and recursively prints all the values of the tree post-order.

7.Write a method(s) that inserts values from a sorted list into a binary search tree in such a way as to maintain balance yet require no explicit balancing.

8.Add method(s) to Node to recursively calculate its size.

9.Add method(s) to Node to recursively calculate its height.

Exercise 1 Solution

public Node minimum() {

return getSmaller() != null ? GetSmaller() : this;

}

Exercise 2 Solution

public Node search(Object value) { return search(value, _root);

}

private Node search(Object value, Node node) { if (node == null) {

return null;

}

int cmp = _comparator.compare(value, node.getValue()); if (cmp == 0) {

return node;

}

return search(value, cmp < 0 ? node.getSmaller() : node.getLarger());

}

522

Answers to Exercises

Exercise 3 Solution

public void inOrderPrint(Node node) { if (node == null) {

return;

}

inOrderPrint(node.getSmaller());

System.out.println(node.getValue());

inOrderPrint(node.getLarger()));

}

Exercise 4 Solution

public void inOrderPrint(Node root) {

for (Node node = root.minimum(); node != null; node = node.successor()) { System.out.println(node.getValue());

}

}

Exercise 5 Solution

public void preOrderPrint(Node node) { if (node == null) {

return;

}

System.out.println(node.getValue());

preOrderPrint(node.getSmaller());

preOrderPrint(node.getLarger()));

}

Exercise 6 Solution

public void postOrderPrint(Node node) { if (node == null) {

return;

}

postOrderPrint(node.getSmaller());

postOrderPrint(node.getLarger()));

System.out.println(node.getValue());

}

Exercise 7 Solution

public void preOrderInsert(BinarySearchTree tree, List list) { preOrderInsert(tree, list, 0, list.size() - 1);

}

private void preOrderInsert(BinarySearchTree tree, List list, int lowerIndex,int upperIndex) {

if (lowerIndex > upperIndex) {

523