Showing preview only (641K chars total). Download the full file or copy to clipboard to get everything.
Repository: bighuang624/Algorithms-notes
Branch: master
Commit: e598780a9ecf
Files: 169
Total size: 543.9 KB
Directory structure:
gitextract_vx5c0m3w/
├── .gitignore
├── README.md
├── code/
│ ├── README.md
│ ├── algs4/
│ │ ├── Alphabet.java
│ │ ├── Bag.java
│ │ ├── BinarySearch.java
│ │ ├── BinaryStdIn.java
│ │ ├── BinaryStdOut.java
│ │ ├── Counter.java
│ │ ├── DepthFirstOrder.java
│ │ ├── Draw.java
│ │ ├── DrawListener.java
│ │ ├── Heap.java
│ │ ├── HexDump.java
│ │ ├── In.java
│ │ ├── IndexMinPQ.java
│ │ ├── Interval1D.java
│ │ ├── Interval2D.java
│ │ ├── MinPQ.java
│ │ ├── Out.java
│ │ ├── Particle.java
│ │ ├── Picture.java
│ │ ├── PictureDump.java
│ │ ├── Point2D.java
│ │ ├── Queue.java
│ │ ├── SET.java
│ │ ├── ST.java
│ │ ├── Stack.java
│ │ ├── StdDraw.java
│ │ ├── StdIn.java
│ │ ├── StdOut.java
│ │ └── StdRandom.java
│ ├── chapter1_1_Programming_Model/
│ │ ├── BinarySearch.java
│ │ ├── BouncingBall.java
│ │ ├── Ex1.java
│ │ ├── Ex10.java
│ │ ├── Ex11.java
│ │ ├── Ex13.java
│ │ ├── Ex14.java
│ │ ├── Ex15.java
│ │ ├── Ex19.java
│ │ ├── Ex2.java
│ │ ├── Ex20.java
│ │ ├── Ex3.java
│ │ ├── Ex30.java
│ │ ├── Ex31.java
│ │ ├── Ex32.java
│ │ ├── Ex6.java
│ │ ├── Ex7a.java
│ │ ├── Ex7b.java
│ │ ├── Ex7c.java
│ │ ├── Ex8.java
│ │ ├── Ex9.java
│ │ ├── RightTriangle.java
│ │ ├── Sattolo.java
│ │ └── StdDrawTest.java
│ ├── chapter1_2_Data_Abstraction/
│ │ ├── Accumulator.java
│ │ ├── AccumulatorTest.java
│ │ ├── Cat.java
│ │ ├── Date.java
│ │ ├── Flips.java
│ │ ├── FlipsMax.java
│ │ ├── Interval2DTest.java
│ │ ├── Rolls.java
│ │ ├── StaticSETofInts.java
│ │ ├── VisualAccumulator.java
│ │ ├── VisualAccumulatorTest.java
│ │ ├── WhiteList.java
│ │ ├── in1.txt
│ │ └── in2.txt
│ ├── chapter1_3_Bags_Queues_Stacks/
│ │ └── ResizingArrayStack.java
│ ├── chapter1_4_Analysis_of_Algorithms/
│ │ ├── DoublingRatio.java
│ │ ├── DoublingTest.java
│ │ ├── Stopwatch.java
│ │ ├── StopwatchTest.java
│ │ └── ThreeSum.java
│ ├── chapter1_5_Case_Study_Union_Find/
│ │ ├── UF.java
│ │ └── WeightedQuickUnionUF.java
│ ├── chapter2_1_Elementary_Sorts/
│ │ ├── Insertion.java
│ │ ├── Selection.java
│ │ ├── Shell.java
│ │ └── SortCompare.java
│ ├── chapter2_2_Mergesort/
│ │ ├── Merge.java
│ │ └── MergeBU.java
│ ├── chapter2_3_Quicksort/
│ │ ├── Ex25.java
│ │ ├── Quick.java
│ │ └── Quick3way.java
│ ├── chapter2_4_Priority_Queues/
│ │ ├── MaxPQ.java
│ │ └── TopM.java
│ ├── chapter3_1_Symbol_Tables/
│ │ ├── BinarySearchST.java
│ │ ├── FrequencyCounter.java
│ │ └── SequentialSearchST.java
│ ├── chapter3_2_Binary_Search_Trees/
│ │ └── BST.java
│ ├── chapter3_4_Hash_Tables/
│ │ ├── LinearProbingHashST.java
│ │ └── SeparateChainingHashST.java
│ ├── chapter3_5_Searching_Applications/
│ │ ├── SparseVector.java
│ │ └── WhiteFilter.java
│ ├── chapter4_1_Undirected_Graphs/
│ │ ├── BreadthFirstPaths.java
│ │ ├── CC.java
│ │ ├── Cycle.java
│ │ ├── DegreesOfSeparation.java
│ │ ├── DepthFirstPaths.java
│ │ ├── DepthFirstSearch.java
│ │ ├── Graph.java
│ │ ├── SymbolGraph.java
│ │ ├── TestCC.java
│ │ ├── TestPaths.java
│ │ ├── TestSearch.java
│ │ ├── TestSymbolGraph.java
│ │ └── TwoColor.java
│ ├── chapter4_2_Directed_Graphs/
│ │ ├── DepthFirstOrder.java
│ │ ├── Digraph.java
│ │ ├── DirectedCycle.java
│ │ ├── DirectedDFS.java
│ │ ├── KosarajuSCC.java
│ │ ├── SymbolDigraph.java
│ │ ├── Topological.java
│ │ └── TransitiveClosure.java
│ ├── chapter4_3_Minimum_Spanning_Tree/
│ │ ├── Edge.java
│ │ ├── EdgeWeightedGraph.java
│ │ ├── KruskalMST.java
│ │ ├── LazyPrimMST.java
│ │ ├── PrimMST.java
│ │ ├── TestMST.java
│ │ └── UF.java
│ ├── chapter4_4_Shortest_Paths/
│ │ ├── DijkstraSP.java
│ │ ├── DirectedEdge.java
│ │ ├── EdgeWeightedDigraph.java
│ │ ├── SP.java
│ │ └── TestSP.java
│ ├── chapter5_3_Substring_Search/
│ │ ├── BoyerMoore.java
│ │ ├── KMP.java
│ │ └── RabinKarp.java
│ ├── chapter6_3_Suffix_Arrays/
│ │ ├── KWIC.java
│ │ ├── LRS.java
│ │ └── SuffixArray.java
│ └── yuki.config.json
├── docs/
│ ├── .nojekyll
│ ├── Context/
│ │ ├── 6.1_事件驱动模拟.md
│ │ ├── 6.2_B-树.md
│ │ ├── 6.3_后缀数组.md
│ │ ├── 6.4_网络流算法.md
│ │ ├── 6.5_问题规约.md
│ │ └── 6.6_不可解性.md
│ ├── Fundamentals/
│ │ ├── 1.3_背包、队列和栈.md
│ │ ├── 1.4_算法分析.md
│ │ └── 1.5_案例研究:union-find算法.md
│ ├── Graphs/
│ │ ├── 4.1_无向图.md
│ │ ├── 4.2_有向图.md
│ │ ├── 4.3_最小生成树.md
│ │ └── 4.4_最短路径.md
│ ├── README.md
│ ├── Searching/
│ │ ├── 3.1_符号表.md
│ │ ├── 3.2_二叉查找树.md
│ │ ├── 3.3_平衡查找树.md
│ │ ├── 3.4_散列表.md
│ │ └── 3.5_应用.md
│ ├── Sorting/
│ │ ├── 2.1_初级排序算法.md
│ │ ├── 2.2_归并排序.md
│ │ ├── 2.3_快速排序.md
│ │ ├── 2.4_优先队列.md
│ │ └── 2.5_应用.md
│ ├── Strings/
│ │ ├── 5.2_单词查找树.md
│ │ └── 5.3_子字符串查找.md
│ ├── _sidebar.md
│ └── index.html
├── package.json
├── 每一节可以再看一遍的题.md
└── 相关问题解决方法.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
================================================
FILE: README.md
================================================
# 《算法(第4版)》笔记及代码
[](http://kyonhuang.top)
## 笔记
推荐阅览 html 版本的笔记,由 [docsify](https://docsify.js.org/#/zh-cn/) 动态生成文档网站。
[在线阅览地址](http://kyonhuang.top/Algorithms-notes/)
## 目录
* [《每一节可以再看一遍的题》](https://github.com/bighuang624/Algorithms-notes/blob/master/每一节可以再看一遍的题.md)
* [《相关问题解决方法》](https://github.com/bighuang624/Algorithms-notes/blob/master/相关问题解决方法.md)
### Fundamentals
* [《1.3_背包、队列和栈》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.3_背包、队列和栈.md)
* [《1.4_算法分析》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.4_算法分析.md)
* [《1.5_案例研究:union-find算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.5_案例研究:union-find算法.md)
### Sorting
* [《2.1_初级排序算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.1_初级排序算法.md)
* [《2.2_归并排序》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.2_归并排序.md)
* [《2.3_快速排序》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.3_快速排序.md)
* [《2.4_优先队列》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.4_优先队列.md)
* [《2.5_应用》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.5_应用.md)
### Searching
* [《3.1_符号表》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.1_符号表.md)
* [《3.2_二叉查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.2_二叉查找树.md)
* [《3.3_平衡查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.3_平衡查找树.md)
* [《3.4_散列表》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.4_散列表.md)
* [《3.5_应用》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.5_应用.md)
### Graphs
* [《4.1_无向图》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.1_无向图.md)
* [《4.2_有向图》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.2_有向图.md)
* [《4.3_最小生成树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.3_最小生成树.md)
* [《4.4_最短路径》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.4_最短路径.md)
### Strings
* [《5.2_单词查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Strings/5.2_单词查找树.md)
* [《5.3_子字符串查找》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Strings/5.3_子字符串查找.md)
### Context
* [《6.3_后缀数组》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.3_后缀数组.md)
* [《6.4_网络流算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.4_网络流算法.md)
* [《6.5_问题规约》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.5_问题规约.md)
* [《6.6_不可解性》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.6_不可解性.md)
## 代码
相关代码详见[代码目录](https://github.com/bighuang624/Algorithms-notes/blob/master/code)
## Cheatsheet
[Algorithms and Data Structures Cheatsheet](https://algs4.cs.princeton.edu/cheatsheet/)

## 参考资料
[算法(第4版)课后练习答案及相关问题解决方案 - 孙强Jimmy的技术博客 - CSDN博客](http://blog.csdn.net/u013541140/article/details/53222770)
================================================
FILE: code/README.md
================================================
# 代码目录
### algs4
* [Alphabet.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Alphabet.java)
* [Bag.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Bag.java)
* [BinarySearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinarySearch.java)
* [BinaryStdIn.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinaryStdIn.java)
* [BinaryStdOut.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinaryStdOut.java)
* [Counter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Counter.java)
* [DepthFirstOrder.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/DepthFirstOrder.java)
* [Draw.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Draw.java)
* [DrawListener.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/DrawListener.java)
* [Heap.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Heap.java)
* [HexDump.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/HexDump.java)
* [In.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/In.java)
* [IndexMinPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/IndexMinPQ.java)
* [Interval1D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Interval1D.java)
* [Interval2D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Interval2D.java)
* [MinPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/MinPQ.java)
* [Out.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Out.java)
* [Particle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Particle.java)
* [Picture.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Picture.java)
* [PictureDump.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/PictureDump.java)
* [Point2D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Point2D.java)
* [Queue.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Queue.java)
* [SET.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/SET.java)
* [ST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/ST.java)
* [Stack.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Stack.java)
* [StdDraw.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdDraw.java)
* [StdIn.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdIn.java)
* [StdOut.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdOut.java)
* [StdRandom.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdRandom.java)
### chapter1_1_Programming_Model
* [BinarySearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/BinarySearch.java)
* [BouncingBall.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/BouncingBall.java)
* [Ex1.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex1.java)
* [Ex10.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex10.java)
* [Ex11.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex11.java)
* [Ex13.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex13.java)
* [Ex14.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex14.java)
* [Ex15.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex15.java)
* [Ex19.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex19.java)
* [Ex2.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex2.java)
* [Ex20.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex20.java)
* [Ex3.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex3.java)
* [Ex30.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex30.java)
* [Ex31.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex31.java)
* [Ex32.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex32.java)
* [Ex6.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex6.java)
* [Ex7a.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7a.java)
* [Ex7b.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7b.java)
* [Ex7c.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7c.java)
* [Ex8.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex8.java)
* [Ex9.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex9.java)
* [RightTriangle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/RightTriangle.java)
* [Sattolo.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Sattolo.java)
* [StdDrawTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/StdDrawTest.java)
### chapter1_2_Data_Abstraction
* [Accumulator.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Accumulator.java)
* [AccumulatorTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/AccumulatorTest.java)
* [Cat.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Cat.java)
* [Date.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Date.java)
* [Flips.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Flips.java)
* [FlipsMax.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/FlipsMax.java)
* [Interval2DTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Interval2DTest.java)
* [Rolls.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Rolls.java)
* [StaticSETofInts.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/StaticSETofInts.java)
* [VisualAccumulator.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/VisualAccumulator.java)
* [VisualAccumulatorTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/VisualAccumulatorTest.java)
* [WhiteList.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/WhiteList.java)
* [in1.txt](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/in1.txt)
* [in2.txt](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/in2.txt)
### chapter1_3_Bags_Queues_Stacks
* [ResizingArrayStack.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_3_Bags_Queues_Stacks/ResizingArrayStack.java)
### chapter1_4_Analysis_of_Algorithms
* [DoublingRatio.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/DoublingRatio.java)
* [DoublingTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/DoublingTest.java)
* [Stopwatch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/Stopwatch.java)
* [StopwatchTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/StopwatchTest.java)
* [ThreeSum.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/ThreeSum.java)
### chapter1_5_Case_Study_Union_Find
* [UF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_5_Case_Study_Union_Find/UF.java)
* [WeightedQuickUnionUF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_5_Case_Study_Union_Find/WeightedQuickUnionUF.java)
### chapter2_1_Elementary_Sorts
* [Insertion.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Insertion.java)
* [Selection.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Selection.java)
* [Shell.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Shell.java)
* [SortCompare.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/SortCompare.java)
### chapter2_2_Mergesort
* [Merge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_2_Mergesort/Merge.java)
* [MergeBU.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_2_Mergesort/MergeBU.java)
### chapter2_3_Quicksort
* [Ex25.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Ex25.java)
* [Quick.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Quick.java)
* [Quick3way.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Quick3way.java)
### chapter2_4_Priority_Queues
* [MaxPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_4_Priority_Queues/MaxPQ.java)
* [TopM.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_4_Priority_Queues/TopM.java)
### chapter2_5_Sorting_Applications
### chapter3_1_Symbol_Tables
* [BinarySearchST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/BinarySearchST.java)
* [FrequencyCounter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/FrequencyCounter.java)
* [SequentialSearchST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/SequentialSearchST.java)
### chapter3_2_Binary_Search_Trees
* [BST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_2_Binary_Search_Trees/BST.java)
### chapter3_4_Hash_Tables
* [LinearProbingHashST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_4_Hash_Tables/LinearProbingHashST.java)
* [SeparateChainingHashST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_4_Hash_Tables/SeparateChainingHashST.java)
### chapter3_5_Searching_Applications
* [SparseVector.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_5_Searching_Applications/SparseVector.java)
* [WhiteFilter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_5_Searching_Applications/WhiteFilter.java)
### chapter4_1_Undirected_Graphs
* [BreadthFirstPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/BreadthFirstPaths.java)
* [CC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/CC.java)
* [Cycle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/Cycle.java)
* [DegreesOfSeparation.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DegreesOfSeparation.java)
* [DepthFirstPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstPaths.java)
* [DepthFirstSearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstSearch.java)
* [Graph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/Graph.java)
* [SymbolGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/SymbolGraph.java)
* [TestCC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestCC.java)
* [TestPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestPaths.java)
* [TestSearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestSearch.java)
* [TestSymbolGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestSymbolGraph.java)
* [TwoColor.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TwoColor.java)
### chapter4_2_Directed_Graphs
* [DepthFirstOrder.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DepthFirstOrder.java)
* [Digraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Digraph.java)
* [DirectedCycle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedCycle.java)
* [DirectedDFS.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedDFS.java)
* [KosarajuSCC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/KosarajuSCC.java)
* [SymbolDigraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/SymbolDigraph.java)
* [Topological.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Topological.java)
* [TransitiveClosure.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/TransitiveClosure.java)
### chapter4_3_Minimum_Spanning_Tree
* [Edge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/Edge.java)
* [EdgeWeightedGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/EdgeWeightedGraph.java)
* [KruskalMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/KruskalMST.java)
* [LazyPrimMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/LazyPrimMST.java)
* [PrimMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/PrimMST.java)
* [TestMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/TestMST.java)
* [UF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/UF.java)
### chapter4_4_Shortest_Paths
* [DijkstraSP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/DijkstraSP.java)
* [DirectedEdge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/DirectedEdge.java)
* [EdgeWeightedDigraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/EdgeWeightedDigraph.java)
* [SP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/SP.java)
* [TestSP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/TestSP.java)
### chapter5_3_Substring_Search
* [BoyerMoore.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/BoyerMoore.java)
* [KMP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/KMP.java)
* [RabinKarp.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/RabinKarp.java)
### chapter6_3_Suffix_Arrays
* [KWIC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/KWIC.java)
* [LRS.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/LRS.java)
* [SuffixArray.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/SuffixArray.java)
================================================
FILE: code/algs4/Alphabet.java
================================================
/******************************************************************************
* Compilation: javac Alphabet.java
* Execution: java Alphabet
* Dependencies: StdOut.java
*
* A data type for alphabets, for use with string-processing code
* that must convert between an alphabet of size R and the integers
* 0 through R-1.
*
* Warning: supports only the basic multilingual plane (BMP), i.e,
* Unicode characters between U+0000 and U+FFFF.
*
******************************************************************************/
package algs4;
public class Alphabet {
/**
* The binary alphabet { 0, 1 }.
*/
public static final Alphabet BINARY = new Alphabet("01");
/**
* The octal alphabet { 0, 1, 2, 3, 4, 5, 6, 7 }.
*/
public static final Alphabet OCTAL = new Alphabet("01234567");
/**
* The decimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.
*/
public static final Alphabet DECIMAL = new Alphabet("0123456789");
/**
* The hexadecimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F }.
*/
public static final Alphabet HEXADECIMAL = new Alphabet("0123456789ABCDEF");
/**
* The DNA alphabet { A, C, T, G }.
*/
public static final Alphabet DNA = new Alphabet("ACGT");
/**
* The lowercase alphabet { a, b, c, ..., z }.
*/
public static final Alphabet LOWERCASE = new Alphabet("abcdefghijklmnopqrstuvwxyz");
/**
* The uppercase alphabet { A, B, C, ..., Z }.
*/
public static final Alphabet UPPERCASE = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
/**
* The protein alphabet { A, C, D, E, F, G, H, I, K, L, M, N, P, Q, R, S, T, V, W, Y }.
*/
public static final Alphabet PROTEIN = new Alphabet("ACDEFGHIKLMNPQRSTVWY");
/**
* The base-64 alphabet (64 characters).
*/
public static final Alphabet BASE64 = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
/**
* The ASCII alphabet (0-127).
*/
public static final Alphabet ASCII = new Alphabet(128);
/**
* The extended ASCII alphabet (0-255).
*/
public static final Alphabet EXTENDED_ASCII = new Alphabet(256);
/**
* The Unicode 16 alphabet (0-65,535).
*/
public static final Alphabet UNICODE16 = new Alphabet(65536);
private char[] alphabet; // the characters in the alphabet
private int[] inverse; // indices
private final int R; // the radix of the alphabet
/**
* Initializes a new alphabet from the given set of characters.
*
* @param alpha the set of characters
*/
public Alphabet(String alpha) {
// check that alphabet contains no duplicate chars
boolean[] unicode = new boolean[Character.MAX_VALUE];
for (int i = 0; i < alpha.length(); i++) {
char c = alpha.charAt(i);
if (unicode[c])
throw new IllegalArgumentException("Illegal alphabet: repeated character = '" + c + "'");
unicode[c] = true;
}
alphabet = alpha.toCharArray();
R = alpha.length();
inverse = new int[Character.MAX_VALUE];
for (int i = 0; i < inverse.length; i++)
inverse[i] = -1;
// can't use char since R can be as big as 65,536
for (int c = 0; c < R; c++)
inverse[alphabet[c]] = c;
}
/**
* Initializes a new alphabet using characters 0 through R-1.
*
* @param radix the number of characters in the alphabet (the radix R)
*/
private Alphabet(int radix) {
this.R = radix;
alphabet = new char[R];
inverse = new int[R];
// can't use char since R can be as big as 65,536
for (int i = 0; i < R; i++)
alphabet[i] = (char) i;
for (int i = 0; i < R; i++)
inverse[i] = i;
}
/**
* Initializes a new alphabet using characters 0 through 255.
*/
public Alphabet() {
this(256);
}
/**
* Returns true if the argument is a character in this alphabet.
*
* @param c the character
* @return {@code true} if {@code c} is a character in this alphabet;
* {@code false} otherwise
*/
public boolean contains(char c) {
return inverse[c] != -1;
}
/**
* Returns the number of characters in this alphabet (the radix).
*
* @return the number of characters in this alphabet
* @deprecated Replaced by {@link #radix()}.
*/
@Deprecated
public int R() {
return R;
}
/**
* Returns the number of characters in this alphabet (the radix).
*
* @return the number of characters in this alphabet
*/
public int radix() {
return R;
}
/**
* Returns the binary logarithm of the number of characters in this alphabet.
*
* @return the binary logarithm (rounded up) of the number of characters in this alphabet
*/
public int lgR() {
int lgR = 0;
for (int t = R-1; t >= 1; t /= 2)
lgR++;
return lgR;
}
/**
* Returns the index corresponding to the argument character.
*
* @param c the character
* @return the index corresponding to the character {@code c}
* @throws IllegalArgumentException unless {@code c} is a character in this alphabet
*/
public int toIndex(char c) {
if (c >= inverse.length || inverse[c] == -1) {
throw new IllegalArgumentException("Character " + c + " not in alphabet");
}
return inverse[c];
}
/**
* Returns the indices corresponding to the argument characters.
*
* @param s the characters
* @return the indices corresponding to the characters {@code s}
* @throws IllegalArgumentException unless every character in {@code s}
* is a character in this alphabet
*/
public int[] toIndices(String s) {
char[] source = s.toCharArray();
int[] target = new int[s.length()];
for (int i = 0; i < source.length; i++)
target[i] = toIndex(source[i]);
return target;
}
/**
* Returns the character corresponding to the argument index.
*
* @param index the index
* @return the character corresponding to the index {@code index}
* @throws IllegalArgumentException unless {@code 0 <= index < R}
*/
public char toChar(int index) {
if (index < 0 || index >= R) {
throw new IndexOutOfBoundsException("Alphabet index out of bounds");
}
return alphabet[index];
}
/**
* Returns the characters corresponding to the argument indices.
*
* @param indices the indices
* @return the characters corresponding to the indices {@code indices}
* @throws IllegalArgumentException unless {@code 0 < indices[i] < R}
* for every {@code i}
*/
public String toChars(int[] indices) {
StringBuilder s = new StringBuilder(indices.length);
for (int i = 0; i < indices.length; i++)
s.append(toChar(indices[i]));
return s.toString();
}
/**
* Unit tests the {@code Alphabet} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int[] encoded1 = Alphabet.BASE64.toIndices("NowIsTheTimeForAllGoodMen");
String decoded1 = Alphabet.BASE64.toChars(encoded1);
StdOut.println(decoded1);
int[] encoded2 = Alphabet.DNA.toIndices("AACGAACGGTTTACCCCG");
String decoded2 = Alphabet.DNA.toChars(encoded2);
StdOut.println(decoded2);
int[] encoded3 = Alphabet.DECIMAL.toIndices("01234567890123456789");
String decoded3 = Alphabet.DECIMAL.toChars(encoded3);
StdOut.println(decoded3);
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Bag.java
================================================
/******************************************************************************
* Compilation: javac Bag.java
* Execution: java Bag < input.txt
* Dependencies: StdIn.java StdOut.java
*
* A generic bag or multiset, implemented using a singly-linked list.
*
* % more tobe.txt
* to be or not to - be - - that - - - is
*
* % java Bag < tobe.txt
* size of bag = 14
* is
* -
* -
* -
* that
* -
* -
* be
* -
* to
* not
* or
* be
* to
*
******************************************************************************/
package algs4;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code Bag} class represents a bag (or multiset) of
* generic items. It supports insertion and iterating over the
* items in arbitrary order.
* <p>
* This implementation uses a singly-linked list with a static nested class Node.
* See {@link LinkedBag} for the version from the
* textbook that uses a non-static nested class.
* The <em>add</em>, <em>isEmpty</em>, and <em>size</em> operations
* take constant time. Iteration takes time proportional to the number of items.
* <p>
* For additional documentation, see <a href="http://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 of an item in this bag
*/
public class Bag<Item> implements Iterable<Item> {
private Node<Item> first; // beginning of bag
private int n; // number of elements in bag
// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty bag.
*/
public Bag() {
first = null;
n = 0;
}
/**
* Returns true if this bag is empty.
*
* @return {@code true} if this bag is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of items in this bag.
*
* @return the number of items in this bag
*/
public int size() {
return n;
}
/**
* Adds the item to this bag.
*
* @param item the item to add to this bag
*/
public void add(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
/**
* Returns an iterator that iterates over the items in this bag in arbitrary order.
*
* @return an iterator that iterates over the items in this bag in arbitrary order
*/
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
}
// an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
/**
* Unit tests the {@code Bag} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
bag.add(item);
}
StdOut.println("size of bag = " + bag.size());
for (String s : bag) {
StdOut.println(s);
}
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/BinarySearch.java
================================================
/******************************************************************************
* Compilation: javac BinarySearch.java
* Execution: java BinarySearch whitelist.txt < input.txt
* Dependencies: In.java StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/11model/tinyW.txt
* http://algs4.cs.princeton.edu/11model/tinyT.txt
* http://algs4.cs.princeton.edu/11model/largeW.txt
* http://algs4.cs.princeton.edu/11model/largeT.txt
*
* % java BinarySearch tinyW.txt < tinyT.txt
* 50
* 99
* 13
*
* % java BinarySearch largeW.txt < largeT.txt | more
* 499569
* 984875
* 295754
* 207807
* 140925
* 161828
* [367,966 total values]
*
******************************************************************************/
package algs4;
import java.util.Arrays;
/**
* The {@code BinarySearch} class provides a static method for binary
* searching for an integer in a sorted array of integers.
* <p>
* The <em>indexOf</em> operations takes logarithmic time in the worst case.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/11model">Section 1.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class BinarySearch {
/**
* This class should not be instantiated.
*/
private BinarySearch() { }
/**
* Returns the index of the specified key in the specified array.
*
* @param a the array of integers, must be sorted in ascending order
* @param key the search key
* @return index of key in array {@code a} if present; {@code -1} otherwise
*/
public static int indexOf(int[] a, int key) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
/**
* Returns the index of the specified key in the specified array.
* This function is poorly named because it does not give the <em>rank</em>
* if the array has duplicate keys or if the key is not in the array.
*
* @param key the search key
* @param a the array of integers, must be sorted in ascending order
* @return index of key in array {@code a} if present; {@code -1} otherwise
* @deprecated Replaced by {@link #indexOf(int[], int)}.
*/
@Deprecated
public static int rank(int key, int[] a) {
return indexOf(a, key);
}
/**
* Reads in a sequence of integers from the whitelist file, specified as
* a command-line argument; reads in integers from standard input;
* prints to standard output those integers that do <em>not</em> appear in the file.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// read the integers from a file
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
// sort the array
Arrays.sort(whitelist);
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
if (BinarySearch.indexOf(whitelist, key) == -1)
StdOut.println(key);
}
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/BinaryStdIn.java
================================================
/******************************************************************************
* Compilation: javac BinaryStdIn.java
* Execution: java BinaryStdIn < input > output
* Dependencies: none
*
* Supports reading binary data from standard input.
*
* % java BinaryStdIn < input.jpg > output.jpg
* % diff input.jpg output.jpg
*
******************************************************************************/
package algs4;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.NoSuchElementException;
/**
* <i>Binary standard input</i>. This class provides methods for reading
* in bits from standard input, either one bit at a time (as a {@code boolean}),
* 8 bits at a time (as a {@code byte} or {@code char}),
* 16 bits at a time (as a {@code short}), 32 bits at a time
* (as an {@code int} or {@code float}), or 64 bits at a time (as a
* {@code double} or {@code long}).
* <p>
* All primitive types are assumed to be represented using their
* standard Java representations, in big-endian (most significant
* byte first) order.
* <p>
* The client should not intermix calls to {@code BinaryStdIn} with calls
* to {@code StdIn} or {@code System.in};
* otherwise unexpected behavior will result.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class BinaryStdIn {
private static BufferedInputStream in = new BufferedInputStream(System.in);
private static final int EOF = -1; // end of file
private static int buffer; // one character buffer
private static int n; // number of bits left in buffer
// static initializer
static {
fillBuffer();
}
// don't instantiate
private BinaryStdIn() { }
private static void fillBuffer() {
try {
buffer = in.read();
n = 8;
}
catch (IOException e) {
System.out.println("EOF");
buffer = EOF;
n = -1;
}
}
/**
* Close this input stream and release any associated system resources.
*/
public static void close() {
try {
in.close();
}
catch (IOException ioe) {
throw new IllegalStateException("Could not close BinaryStdIn", ioe);
}
}
/**
* Returns true if standard input is empty.
* @return true if and only if standard input is empty
*/
public static boolean isEmpty() {
return buffer == EOF;
}
/**
* Reads the next bit of data from standard input and return as a boolean.
*
* @return the next bit of data from standard input as a {@code boolean}
* @throws NoSuchElementException if standard input is empty
*/
public static boolean readBoolean() {
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
n--;
boolean bit = ((buffer >> n) & 1) == 1;
if (n == 0) fillBuffer();
return bit;
}
/**
* Reads the next 8 bits from standard input and return as an 8-bit char.
* Note that {@code char} is a 16-bit type;
* to read the next 16 bits as a char, use {@code readChar(16)}.
*
* @return the next 8 bits of data from standard input as a {@code char}
* @throws NoSuchElementException if there are fewer than 8 bits available on standard input
*/
public static char readChar() {
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
// special case when aligned byte
if (n == 8) {
int x = buffer;
fillBuffer();
return (char) (x & 0xff);
}
// combine last n bits of current buffer with first 8-n bits of new buffer
int x = buffer;
x <<= (8 - n);
int oldN = n;
fillBuffer();
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
n = oldN;
x |= (buffer >>> n);
return (char) (x & 0xff);
// the above code doesn't quite work for the last character if n = 8
// because buffer will be -1, so there is a special case for aligned byte
}
/**
* Reads the next r bits from standard input and return as an r-bit character.
*
* @param r number of bits to read.
* @return the next r bits of data from standard input as a {@code char}
* @throws NoSuchElementException if there are fewer than {@code r} bits available on standard input
* @throws IllegalArgumentException unless {@code 1 <= r <= 16}
*/
public static char readChar(int r) {
if (r < 1 || r > 16) throw new IllegalArgumentException("Illegal value of r = " + r);
// optimize r = 8 case
if (r == 8) return readChar();
char x = 0;
for (int i = 0; i < r; i++) {
x <<= 1;
boolean bit = readBoolean();
if (bit) x |= 1;
}
return x;
}
/**
* Reads the remaining bytes of data from standard input and return as a string.
*
* @return the remaining bytes of data from standard input as a {@code String}
* @throws NoSuchElementException if standard input is empty or if the number of bits
* available on standard input is not a multiple of 8 (byte-aligned)
*/
public static String readString() {
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
StringBuilder sb = new StringBuilder();
while (!isEmpty()) {
char c = readChar();
sb.append(c);
}
return sb.toString();
}
/**
* Reads the next 16 bits from standard input and return as a 16-bit short.
*
* @return the next 16 bits of data from standard input as a {@code short}
* @throws NoSuchElementException if there are fewer than 16 bits available on standard input
*/
public static short readShort() {
short x = 0;
for (int i = 0; i < 2; i++) {
char c = readChar();
x <<= 8;
x |= c;
}
return x;
}
/**
* Reads the next 32 bits from standard input and return as a 32-bit int.
*
* @return the next 32 bits of data from standard input as a {@code int}
* @throws NoSuchElementException if there are fewer than 32 bits available on standard input
*/
public static int readInt() {
int x = 0;
for (int i = 0; i < 4; i++) {
char c = readChar();
x <<= 8;
x |= c;
}
return x;
}
/**
* Reads the next r bits from standard input and return as an r-bit int.
*
* @param r number of bits to read.
* @return the next r bits of data from standard input as a {@code int}
* @throws NoSuchElementException if there are fewer than {@code r} bits available on standard input
* @throws IllegalArgumentException unless {@code 1 <= r <= 32}
*/
public static int readInt(int r) {
if (r < 1 || r > 32) throw new IllegalArgumentException("Illegal value of r = " + r);
// optimize r = 32 case
if (r == 32) return readInt();
int x = 0;
for (int i = 0; i < r; i++) {
x <<= 1;
boolean bit = readBoolean();
if (bit) x |= 1;
}
return x;
}
/**
* Reads the next 64 bits from standard input and return as a 64-bit long.
*
* @return the next 64 bits of data from standard input as a {@code long}
* @throws NoSuchElementException if there are fewer than 64 bits available on standard input
*/
public static long readLong() {
long x = 0;
for (int i = 0; i < 8; i++) {
char c = readChar();
x <<= 8;
x |= c;
}
return x;
}
/**
* Reads the next 64 bits from standard input and return as a 64-bit double.
*
* @return the next 64 bits of data from standard input as a {@code double}
* @throws NoSuchElementException if there are fewer than 64 bits available on standard input
*/
public static double readDouble() {
return Double.longBitsToDouble(readLong());
}
/**
* Reads the next 32 bits from standard input and return as a 32-bit float.
*
* @return the next 32 bits of data from standard input as a {@code float}
* @throws NoSuchElementException if there are fewer than 32 bits available on standard input
*/
public static float readFloat() {
return Float.intBitsToFloat(readInt());
}
/**
* Reads the next 8 bits from standard input and return as an 8-bit byte.
*
* @return the next 8 bits of data from standard input as a {@code byte}
* @throws NoSuchElementException if there are fewer than 8 bits available on standard input
*/
public static byte readByte() {
char c = readChar();
return (byte) (c & 0xff);
}
/**
* Test client. Reads in a binary input file from standard input and writes
* it to standard output.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// read one 8-bit char at a time
while (!BinaryStdIn.isEmpty()) {
char c = BinaryStdIn.readChar();
BinaryStdOut.write(c);
}
BinaryStdOut.flush();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/BinaryStdOut.java
================================================
/******************************************************************************
* Compilation: javac BinaryStdOut.java
* Execution: java BinaryStdOut
* Dependencies: none
*
* Write binary data to standard output, either one 1-bit boolean,
* one 8-bit char, one 32-bit int, one 64-bit double, one 32-bit float,
* or one 64-bit long at a time.
*
* The bytes written are not aligned.
*
******************************************************************************/
package algs4;
import java.io.BufferedOutputStream;
import java.io.IOException;
/**
* <i>Binary standard output</i>. This class provides methods for converting
* primtive type variables ({@code boolean}, {@code byte}, {@code char},
* {@code int}, {@code long}, {@code float}, and {@code double})
* to sequences of bits and writing them to standard output.
* Uses big-endian (most-significant byte first).
* <p>
* The client must {@code flush()} the output stream when finished writing bits.
* <p>
* The client should not intermixing calls to {@code BinaryStdOut} with calls
* to {@code StdOut} or {@code System.out}; otherwise unexpected behavior
* will result.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class BinaryStdOut {
private static BufferedOutputStream out = new BufferedOutputStream(System.out);
private static int buffer; // 8-bit buffer of bits to write out
private static int n; // number of bits remaining in buffer
// don't instantiate
private BinaryStdOut() { }
/**
* Write the specified bit to standard output.
*/
private static void writeBit(boolean bit) {
// add bit to buffer
buffer <<= 1;
if (bit) buffer |= 1;
// if buffer is full (8 bits), write out as a single byte
n++;
if (n == 8) clearBuffer();
}
/**
* Write the 8-bit byte to standard output.
*/
private static void writeByte(int x) {
assert x >= 0 && x < 256;
// optimized if byte-aligned
if (n == 0) {
try {
out.write(x);
}
catch (IOException e) {
e.printStackTrace();
}
return;
}
// otherwise write one bit at a time
for (int i = 0; i < 8; i++) {
boolean bit = ((x >>> (8 - i - 1)) & 1) == 1;
writeBit(bit);
}
}
// write out any remaining bits in buffer to standard output, padding with 0s
private static void clearBuffer() {
if (n == 0) return;
if (n > 0) buffer <<= (8 - n);
try {
out.write(buffer);
}
catch (IOException e) {
e.printStackTrace();
}
n = 0;
buffer = 0;
}
/**
* Flush standard output, padding 0s if number of bits written so far
* is not a multiple of 8.
*/
public static void flush() {
clearBuffer();
try {
out.flush();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Flush and close standard output. Once standard output is closed, you can no
* longer write bits to it.
*/
public static void close() {
flush();
try {
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Write the specified bit to standard output.
* @param x the {@code boolean} to write.
*/
public static void write(boolean x) {
writeBit(x);
}
/**
* Write the 8-bit byte to standard output.
* @param x the {@code byte} to write.
*/
public static void write(byte x) {
writeByte(x & 0xff);
}
/**
* Write the 32-bit int to standard output.
* @param x the {@code int} to write.
*/
public static void write(int x) {
writeByte((x >>> 24) & 0xff);
writeByte((x >>> 16) & 0xff);
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
/**
* Write the r-bit int to standard output.
* @param x the {@code int} to write.
* @param r the number of relevant bits in the char.
* @throws IllegalArgumentException if {@code r} is not between 1 and 32.
* @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.
*/
public static void write(int x, int r) {
if (r == 32) {
write(x);
return;
}
if (r < 1 || r > 32) throw new IllegalArgumentException("Illegal value for r = " + r);
if (x < 0 || x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
for (int i = 0; i < r; i++) {
boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
writeBit(bit);
}
}
/**
* Write the 64-bit double to standard output.
* @param x the {@code double} to write.
*/
public static void write(double x) {
write(Double.doubleToRawLongBits(x));
}
/**
* Write the 64-bit long to standard output.
* @param x the {@code long} to write.
*/
public static void write(long x) {
writeByte((int) ((x >>> 56) & 0xff));
writeByte((int) ((x >>> 48) & 0xff));
writeByte((int) ((x >>> 40) & 0xff));
writeByte((int) ((x >>> 32) & 0xff));
writeByte((int) ((x >>> 24) & 0xff));
writeByte((int) ((x >>> 16) & 0xff));
writeByte((int) ((x >>> 8) & 0xff));
writeByte((int) ((x >>> 0) & 0xff));
}
/**
* Write the 32-bit float to standard output.
* @param x the {@code float} to write.
*/
public static void write(float x) {
write(Float.floatToRawIntBits(x));
}
/**
* Write the 16-bit int to standard output.
* @param x the {@code short} to write.
*/
public static void write(short x) {
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
/**
* Write the 8-bit char to standard output.
* @param x the {@code char} to write.
* @throws IllegalArgumentException if {@code x} is not betwen 0 and 255.
*/
public static void write(char x) {
if (x < 0 || x >= 256) throw new IllegalArgumentException("Illegal 8-bit char = " + x);
writeByte(x);
}
/**
* Write the r-bit char to standard output.
* @param x the {@code char} to write.
* @param r the number of relevant bits in the char.
* @throws IllegalArgumentException if {@code r} is not between 1 and 16.
* @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.
*/
public static void write(char x, int r) {
if (r == 8) {
write(x);
return;
}
if (r < 1 || r > 16) throw new IllegalArgumentException("Illegal value for r = " + r);
if (x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
for (int i = 0; i < r; i++) {
boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
writeBit(bit);
}
}
/**
* Write the string of 8-bit characters to standard output.
* @param s the {@code String} to write.
* @throws IllegalArgumentException if any character in the string is not
* between 0 and 255.
*/
public static void write(String s) {
for (int i = 0; i < s.length(); i++)
write(s.charAt(i));
}
/**
* Write the String of r-bit characters to standard output.
* @param s the {@code String} to write.
* @param r the number of relevants bits in each character.
* @throws IllegalArgumentException if r is not between 1 and 16.
* @throws IllegalArgumentException if any character in the string is not
* between 0 and 2<sup>r</sup> - 1.
*/
public static void write(String s, int r) {
for (int i = 0; i < s.length(); i++)
write(s.charAt(i), r);
}
/**
* Test client.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
// write n integers to binary standard output
for (int i = 0; i < m; i++) {
BinaryStdOut.write(i);
}
BinaryStdOut.flush();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Counter.java
================================================
/******************************************************************************
* Compilation: javac Counter.java
* Execution: java Counter n trials
* Dependencies: StdRandom.java StdOut.java
*
* A mutable data type for an integer counter.
*
* The test clients create n counters and performs trials increment
* operations on random counters.
*
* java Counter 6 600000
* 100140 counter0
* 100273 counter1
* 99848 counter2
* 100129 counter3
* 99973 counter4
* 99637 counter5
*
******************************************************************************/
package algs4;
/**
* The {@code Counter} class is a mutable data type to encapsulate a counter.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/12oop">Section 1.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Counter implements Comparable<Counter> {
private final String name; // counter name
private int count = 0; // current value
/**
* Initializes a new counter starting at 0, with the given id.
*
* @param id the name of the counter
*/
public Counter(String id) {
name = id;
}
/**
* Increments the counter by 1.
*/
public void increment() {
count++;
}
/**
* Returns the current value of this counter.
*
* @return the current value of this counter
*/
public int tally() {
return count;
}
/**
* Returns a string representation of this counter.
*
* @return a string representation of this counter
*/
public String toString() {
return count + " " + name;
}
/**
* Compares this counter to the specified counter.
*
* @param that the other counter
* @return {@code 0} if the value of this counter equals
* the value of that counter; a negative integer if
* the value of this counter is less than the value of
* that counter; and a positive integer if the value
* of this counter is greater than the value of that
* counter
*/
@Override
public int compareTo(Counter that) {
if (this.count < that.count) return -1;
else if (this.count > that.count) return +1;
else return 0;
}
/**
* Reads two command-line integers n and trials; creates n counters;
* increments trials counters at random; and prints results.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
// create n counters
Counter[] hits = new Counter[n];
for (int i = 0; i < n; i++) {
hits[i] = new Counter("counter" + i);
}
// increment trials counters at random
for (int t = 0; t < trials; t++) {
hits[StdRandom.uniform(n)].increment();
}
// print results
for (int i = 0; i < n; i++) {
StdOut.println(hits[i]);
}
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/DepthFirstOrder.java
================================================
///******************************************************************************
// * Compilation: javac DepthFirstOrder.java
// * Execution: java DepthFirstOrder digraph.txt
// * Dependencies: Digraph.java Queue.java Stack.java StdOut.java
// * EdgeWeightedDigraph.java DirectedEdge.java
// * Data files: http://algs4.cs.princeton.edu/42digraph/tinyDAG.txt
// * http://algs4.cs.princeton.edu/42digraph/tinyDG.txt
// *
// * Compute preorder and postorder for a digraph or edge-weighted digraph.
// * Runs in O(E + V) time.
// *
// * % java DepthFirstOrder tinyDAG.txt
// * v pre post
// * --------------
// * 0 0 8
// * 1 3 2
// * 2 9 10
// * 3 10 9
// * 4 2 0
// * 5 1 1
// * 6 4 7
// * 7 11 11
// * 8 12 12
// * 9 5 6
// * 10 8 5
// * 11 6 4
// * 12 7 3
// * Preorder: 0 5 4 1 6 9 11 12 10 2 3 7 8
// * Postorder: 4 5 1 12 11 10 9 6 0 3 2 7 8
// * Reverse postorder: 8 7 2 3 0 6 9 10 11 12 1 5 4
// *
// ******************************************************************************/
//
//package algs4;
//
//import com.jimmysun.algorithms.chapter4_2.Digraph;
//import com.jimmysun.algorithms.chapter4_4.DirectedEdge;
//import com.jimmysun.algorithms.chapter4_4.EdgeWeightedDigraph;
//
///**
// * The {@code DepthFirstOrder} class represents a data type for
// * determining depth-first search ordering of the vertices in a digraph
// * or edge-weighted digraph, including preorder, postorder, and reverse postorder.
// * <p>
// * This implementation uses depth-first search.
// * The constructor takes time proportional to <em>V</em> + <em>E</em>
// * (in the worst case),
// * where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
// * Afterwards, the <em>preorder</em>, <em>postorder</em>, and <em>reverse postorder</em>
// * operation takes take time proportional to <em>V</em>.
// * <p>
// * For additional documentation,
// * see <a href="http://algs4.cs.princeton.edu/42digraph">Section 4.2</a> of
// * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
// *
// * @author Robert Sedgewick
// * @author Kevin Wayne
// */
//public class DepthFirstOrder {
// private boolean[] marked; // marked[v] = has v been marked in dfs?
// private int[] pre; // pre[v] = preorder number of v
// private int[] post; // post[v] = postorder number of v
// private Queue<Integer> preorder; // vertices in preorder
// private Queue<Integer> postorder; // vertices in postorder
// private int preCounter; // counter or preorder numbering
// private int postCounter; // counter for postorder numbering
//
// /**
// * Determines a depth-first order for the digraph {@code G}.
// * @param G the digraph
// */
// public DepthFirstOrder(Digraph G) {
// pre = new int[G.V()];
// post = new int[G.V()];
// postorder = new Queue<Integer>();
// preorder = new Queue<Integer>();
// marked = new boolean[G.V()];
// for (int v = 0; v < G.V(); v++)
// if (!marked[v]) dfs(G, v);
//
// assert check();
// }
//
// /**
// * Determines a depth-first order for the edge-weighted digraph {@code G}.
// * @param G the edge-weighted digraph
// */
// public DepthFirstOrder(EdgeWeightedDigraph G) {
// pre = new int[G.V()];
// post = new int[G.V()];
// postorder = new Queue<Integer>();
// preorder = new Queue<Integer>();
// marked = new boolean[G.V()];
// for (int v = 0; v < G.V(); v++)
// if (!marked[v]) dfs(G, v);
// }
//
// // run DFS in digraph G from vertex v and compute preorder/postorder
// private void dfs(Digraph G, int v) {
// marked[v] = true;
// pre[v] = preCounter++;
// preorder.enqueue(v);
// for (int w : G.adj(v)) {
// if (!marked[w]) {
// dfs(G, w);
// }
// }
// postorder.enqueue(v);
// post[v] = postCounter++;
// }
//
// // run DFS in edge-weighted digraph G from vertex v and compute preorder/postorder
// private void dfs(EdgeWeightedDigraph G, int v) {
// marked[v] = true;
// pre[v] = preCounter++;
// preorder.enqueue(v);
// for (DirectedEdge e : G.adj(v)) {
// int w = e.to();
// if (!marked[w]) {
// dfs(G, w);
// }
// }
// postorder.enqueue(v);
// post[v] = postCounter++;
// }
//
// /**
// * Returns the preorder number of vertex {@code v}.
// * @param v the vertex
// * @return the preorder number of vertex {@code v}
// * @throws IllegalArgumentException unless {@code 0 <= v < V}
// */
// public int pre(int v) {
// validateVertex(v);
// return pre[v];
// }
//
// /**
// * Returns the postorder number of vertex {@code v}.
// * @param v the vertex
// * @return the postorder number of vertex {@code v}
// * @throws IllegalArgumentException unless {@code 0 <= v < V}
// */
// public int post(int v) {
// validateVertex(v);
// return post[v];
// }
//
// /**
// * Returns the vertices in postorder.
// * @return the vertices in postorder, as an iterable of vertices
// */
// public Iterable<Integer> post() {
// return postorder;
// }
//
// /**
// * Returns the vertices in preorder.
// * @return the vertices in preorder, as an iterable of vertices
// */
// public Iterable<Integer> pre() {
// return preorder;
// }
//
// /**
// * Returns the vertices in reverse postorder.
// * @return the vertices in reverse postorder, as an iterable of vertices
// */
// public Iterable<Integer> reversePost() {
// Stack<Integer> reverse = new Stack<Integer>();
// for (int v : postorder)
// reverse.push(v);
// return reverse;
// }
//
//
// // check that pre() and post() are consistent with pre(v) and post(v)
// private boolean check() {
//
// // check that post(v) is consistent with post()
// int r = 0;
// for (int v : post()) {
// if (post(v) != r) {
// StdOut.println("post(v) and post() inconsistent");
// return false;
// }
// r++;
// }
//
// // check that pre(v) is consistent with pre()
// r = 0;
// for (int v : pre()) {
// if (pre(v) != r) {
// StdOut.println("pre(v) and pre() inconsistent");
// return false;
// }
// r++;
// }
//
// return true;
// }
//
// // throw an IllegalArgumentException unless {@code 0 <= v < V}
// private void validateVertex(int v) {
// int V = marked.length;
// if (v < 0 || v >= V)
// throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
// }
//
// /**
// * Unit tests the {@code DepthFirstOrder} data type.
// *
// * @param args the command-line arguments
// */
// public static void main(String[] args) {
// In in = new In(args[0]);
// Digraph G = new Digraph(in);
//
// DepthFirstOrder dfs = new DepthFirstOrder(G);
// StdOut.println(" v pre post");
// StdOut.println("--------------");
// for (int v = 0; v < G.V(); v++) {
// StdOut.printf("%4d %4d %4d\n", v, dfs.pre(v), dfs.post(v));
// }
//
// StdOut.print("Preorder: ");
// for (int v : dfs.pre()) {
// StdOut.print(v + " ");
// }
// StdOut.println();
//
// StdOut.print("Postorder: ");
// for (int v : dfs.post()) {
// StdOut.print(v + " ");
// }
// StdOut.println();
//
// StdOut.print("Reverse postorder: ");
// for (int v : dfs.reversePost()) {
// StdOut.print(v + " ");
// }
// StdOut.println();
//
//
// }
//
//}
//
///******************************************************************************
// * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
// *
// * This file is part of algs4.jar, which accompanies the textbook
// *
// * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
// * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
// * http://algs4.cs.princeton.edu
// *
// *
// * algs4.jar is free software: you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * algs4.jar is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with algs4.jar. If not, see http://www.gnu.org/licenses.
// ******************************************************************************/
================================================
FILE: code/algs4/Draw.java
================================================
/******************************************************************************
* Compilation: javac Draw.java
* Execution: java Draw
* Dependencies: none
*
* Drawing library. This class provides a basic capability for creating
* drawings with your programs. It uses a simple graphics model that
* allows you to create drawings consisting of points, lines, and curves
* in a window on your computer and to save the drawings to a file.
* This is the object-oriented version of standard draw; it supports
* multiple indepedent drawing windows.
*
* Todo
* ----
* - Add support for gradient fill, etc.
*
* Remarks
* -------
* - don't use AffineTransform for rescaling since it inverts
* images and strings
* - careful using setFont in inner loop within an animation -
* it can cause flicker
*
******************************************************************************/
package algs4;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DirectColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.TreeSet;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
/**
* <i>Draw</i>. This class provides a basic capability for
* creating drawings with your programs. It uses a simple graphics model that
* allows you to create drawings consisting of points, lines, and curves
* in a window on your computer and to save the drawings to a file.
* This is the object-oriented version of standard draw; it supports
* multiple indepedent drawing windows.
* <p>
* For additional documentation, see <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Computer Science: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class Draw implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
/**
* The color black.
*/
public static final Color BLACK = Color.BLACK;
/**
* The color blue.
*/
public static final Color BLUE = Color.BLUE;
/**
* The color cyan.
*/
public static final Color CYAN = Color.CYAN;
/**
* The color dark gray.
*/
public static final Color DARK_GRAY = Color.DARK_GRAY;
/**
* The color gray.
*/
public static final Color GRAY = Color.GRAY;
/**
* The color green.
*/
public static final Color GREEN = Color.GREEN;
/**
* The color light gray.
*/
public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;
/**
* The color magenta.
*/
public static final Color MAGENTA = Color.MAGENTA;
/**
* The color orange.
*/
public static final Color ORANGE = Color.ORANGE;
/**
* The color pink.
*/
public static final Color PINK = Color.PINK;
/**
* The color red.
*/
public static final Color RED = Color.RED;
/**
* The color white.
*/
public static final Color WHITE = Color.WHITE;
/**
* The color yellow.
*/
public static final Color YELLOW = Color.YELLOW;
/**
* Shade of blue used in Introduction to Programming in Java.
* It is Pantone 300U. The RGB values are approximately (9, 90, 166).
*/
public static final Color BOOK_BLUE = new Color(9, 90, 166);
/**
* Shade of light blue used in Introduction to Programming in Java.
* The RGB values are approximately (103, 198, 243).
*/
public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243);
/**
* Shade of red used in <em>Algorithms, 4th edition</em>.
* It is Pantone 1805U. The RGB values are approximately (150, 35, 31).
*/
public static final Color BOOK_RED = new Color(150, 35, 31);
// default colors
private static final Color DEFAULT_PEN_COLOR = BLACK;
private static final Color DEFAULT_CLEAR_COLOR = WHITE;
// boundary of drawing canvas, 0% border
private static final double BORDER = 0.0;
private static final double DEFAULT_XMIN = 0.0;
private static final double DEFAULT_XMAX = 1.0;
private static final double DEFAULT_YMIN = 0.0;
private static final double DEFAULT_YMAX = 1.0;
// default canvas size is SIZE-by-SIZE
private static final int DEFAULT_SIZE = 512;
// default pen radius
private static final double DEFAULT_PEN_RADIUS = 0.002;
// default font
private static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 16);
// current pen color
private Color penColor;
// canvas size
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
// current pen radius
private double penRadius;
// show we draw immediately or wait until next show?
private boolean defer = false;
private double xmin, ymin, xmax, ymax;
// name of window
private String name = "Draw";
// for synchronization
private final Object mouseLock = new Object();
private final Object keyLock = new Object();
// current font
private Font font;
// the JLabel for drawing
private JLabel draw;
// double buffered graphics
private BufferedImage offscreenImage, onscreenImage;
private Graphics2D offscreen, onscreen;
// the frame for drawing to the screen
private JFrame frame = new JFrame();
// mouse state
private boolean mousePressed = false;
private double mouseX = 0;
private double mouseY = 0;
// keyboard state
private final LinkedList<Character> keysTyped = new LinkedList<Character>();
private final TreeSet<Integer> keysDown = new TreeSet<Integer>();
// event-based listeners
private final ArrayList<DrawListener> listeners = new ArrayList<DrawListener>();
/**
* Initializes an empty drawing object with the given name.
*
* @param name the title of the drawing window.
*/
public Draw(String name) {
this.name = name;
init();
}
/**
* Initializes an empty drawing object.
*/
public Draw() {
init();
}
private void init() {
if (frame != null) frame.setVisible(false);
frame = new JFrame();
offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
onscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
offscreen = offscreenImage.createGraphics();
onscreen = onscreenImage.createGraphics();
setXscale();
setYscale();
offscreen.setColor(DEFAULT_CLEAR_COLOR);
offscreen.fillRect(0, 0, width, height);
setPenColor();
setPenRadius();
setFont();
clear();
// add antialiasing
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
offscreen.addRenderingHints(hints);
// frame stuff
ImageIcon icon = new ImageIcon(onscreenImage);
draw = new JLabel(icon);
draw.addMouseListener(this);
draw.addMouseMotionListener(this);
frame.setContentPane(draw);
frame.addKeyListener(this); // JLabel cannot get keyboard focus
frame.setResizable(false);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes all windows
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // closes only current window
frame.setTitle(name);
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.requestFocusInWindow();
frame.setVisible(true);
}
/**
* Sets the upper-left hand corner of the drawing window to be (x, y), where (0, 0) is upper left.
*
* @param x the number of pixels from the left
* @param y the number of pixels from the top
* @throws IllegalArgumentException if the width or height is 0 or negative
*/
public void setLocationOnScreen(int x, int y) {
if (x <= 0 || y <= 0) throw new IllegalArgumentException();
frame.setLocation(x, y);
}
/**
* Sets the default close operation.
*
* @param value the value, typically {@code JFrame.EXIT_ON_CLOSE}
* (close all windows) or {@code JFrame.DISPOSE_ON_CLOSE}
* (close current window)
*/
public void setDefaultCloseOperation(int value) {
frame.setDefaultCloseOperation(value);
}
/**
* Sets the canvas (drawing area) to be <em>width</em>-by-<em>height</em> pixels.
* This also erases the current drawing and resets the coordinate system, pen radius,
* pen color, and font back to their default values.
* Ordinarly, this method is called once, at the very beginning of a program.
*
* @param canvasWidth the width as a number of pixels
* @param canvasHeight the height as a number of pixels
* @throws IllegalArgumentException unless both {@code canvasWidth}
* and {@code canvasHeight} are positive
*/
public void setCanvasSize(int canvasWidth, int canvasHeight) {
if (canvasWidth < 1 || canvasHeight < 1) {
throw new IllegalArgumentException("width and height must be positive");
}
width = canvasWidth;
height = canvasHeight;
init();
}
// create the menu bar (changed to private)
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuItem1 = new JMenuItem(" Save... ");
menuItem1.addActionListener(this);
menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuItem1);
return menuBar;
}
/***************************************************************************
* User and screen coordinate systems.
***************************************************************************/
/**
* Sets the x-scale to be the default (between 0.0 and 1.0).
*/
public void setXscale() {
setXscale(DEFAULT_XMIN, DEFAULT_XMAX);
}
/**
* Sets the y-scale to be the default (between 0.0 and 1.0).
*/
public void setYscale() {
setYscale(DEFAULT_YMIN, DEFAULT_YMAX);
}
/**
* Sets the x-scale.
*
* @param min the minimum value of the x-scale
* @param max the maximum value of the x-scale
*/
public void setXscale(double min, double max) {
double size = max - min;
xmin = min - BORDER * size;
xmax = max + BORDER * size;
}
/**
* Sets the y-scale.
*
* @param min the minimum value of the y-scale
* @param max the maximum value of the y-scale
*/
public void setYscale(double min, double max) {
double size = max - min;
ymin = min - BORDER * size;
ymax = max + BORDER * size;
}
// helper functions that scale from user coordinates to screen coordinates and back
private double scaleX(double x) { return width * (x - xmin) / (xmax - xmin); }
private double scaleY(double y) { return height * (ymax - y) / (ymax - ymin); }
private double factorX(double w) { return w * width / Math.abs(xmax - xmin); }
private double factorY(double h) { return h * height / Math.abs(ymax - ymin); }
private double userX(double x) { return xmin + x * (xmax - xmin) / width; }
private double userY(double y) { return ymax - y * (ymax - ymin) / height; }
/**
* Clears the screen to the default color (white).
*/
public void clear() {
clear(DEFAULT_CLEAR_COLOR);
}
/**
* Clears the screen to the given color.
*
* @param color the color to make the background
*/
public void clear(Color color) {
offscreen.setColor(color);
offscreen.fillRect(0, 0, width, height);
offscreen.setColor(penColor);
draw();
}
/**
* Gets the current pen radius.
*
* @return the current pen radius
*/
public double getPenRadius() {
return penRadius;
}
/**
* Sets the pen size to the default (.002).
*/
public void setPenRadius() {
setPenRadius(DEFAULT_PEN_RADIUS);
}
/**
* Sets the radius of the pen to the given size.
*
* @param r the radius of the pen
* @throws IllegalArgumentException if r is negative
*/
public void setPenRadius(double r) {
if (r < 0) throw new IllegalArgumentException("pen radius must be positive");
penRadius = r * DEFAULT_SIZE;
BasicStroke stroke = new BasicStroke((float) penRadius, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
// BasicStroke stroke = new BasicStroke((float) penRadius);
offscreen.setStroke(stroke);
}
/**
* Gets the current pen color.
*
* @return the current pen color
*/
public Color getPenColor() {
return penColor;
}
/**
* Sets the pen color to the default color (black).
*/
public void setPenColor() {
setPenColor(DEFAULT_PEN_COLOR);
}
/**
* Sets the pen color to the given color.
*
* @param color the color to make the pen
*/
public void setPenColor(Color color) {
penColor = color;
offscreen.setColor(penColor);
}
/**
* Sets the pen color to the given RGB color.
*
* @param red the amount of red (between 0 and 255)
* @param green the amount of green (between 0 and 255)
* @param blue the amount of blue (between 0 and 255)
* @throws IllegalArgumentException if the amount of red, green, or blue are outside prescribed range
*/
public void setPenColor(int red, int green, int blue) {
if (red < 0 || red >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
if (green < 0 || green >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
if (blue < 0 || blue >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
setPenColor(new Color(red, green, blue));
}
/**
* Turns on xor mode.
*/
public void xorOn() {
offscreen.setXORMode(DEFAULT_CLEAR_COLOR);
}
/**
* Turns off xor mode.
*/
public void xorOff() {
offscreen.setPaintMode();
}
/**
* Gets the current {@code JLabel} for use in some other GUI.
*
* @return the current {@code JLabel}
*/
public JLabel getJLabel() {
return draw;
}
/**
* Gets the current font.
*
* @return the current font
*/
public Font getFont() {
return font;
}
/**
* Sets the font to the default font (sans serif, 16 point).
*/
public void setFont() {
setFont(DEFAULT_FONT);
}
/**
* Sets the font to the given value.
*
* @param font the font
*/
public void setFont(Font font) {
this.font = font;
}
/***************************************************************************
* Drawing geometric shapes.
***************************************************************************/
/**
* Draws a line from (x0, y0) to (x1, y1).
*
* @param x0 the x-coordinate of the starting point
* @param y0 the y-coordinate of the starting point
* @param x1 the x-coordinate of the destination point
* @param y1 the y-coordinate of the destination point
*/
public void line(double x0, double y0, double x1, double y1) {
offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1)));
draw();
}
/**
* Draws one pixel at (x, y).
*
* @param x the x-coordinate of the pixel
* @param y the y-coordinate of the pixel
*/
private void pixel(double x, double y) {
offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);
}
/**
* Draws a point at (x, y).
*
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
*/
public void point(double x, double y) {
double xs = scaleX(x);
double ys = scaleY(y);
double r = penRadius;
// double ws = factorX(2*r);
// double hs = factorY(2*r);
// if (ws <= 1 && hs <= 1) pixel(x, y);
if (r <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - r/2, ys - r/2, r, r));
draw();
}
/**
* Draws a circle of radius r, centered on (x, y).
*
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public void circle(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("circle radius can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a filled circle of radius r, centered on (x, y).
*
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public void filledCircle(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("circle radius can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws an ellipse with given semimajor and semiminor axes, centered on (x, y).
*
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either of the axes are negative
*/
public void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
if (semiMajorAxis < 0) throw new IllegalArgumentException("ellipse semimajor axis can't be negative");
if (semiMinorAxis < 0) throw new IllegalArgumentException("ellipse semiminor axis can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws an ellipse with given semimajor and semiminor axes, centered on (x, y).
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either of the axes are negative
*/
public void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
if (semiMajorAxis < 0) throw new IllegalArgumentException("ellipse semimajor axis can't be negative");
if (semiMinorAxis < 0) throw new IllegalArgumentException("ellipse semiminor axis can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws an arc of radius r, centered on (x, y), from angle1 to angle2 (in degrees).
*
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if the radius of the circle is negative
*/
public void arc(double x, double y, double r, double angle1, double angle2) {
if (r < 0) throw new IllegalArgumentException("arc radius can't be negative");
while (angle2 < angle1) angle2 += 360;
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN));
draw();
}
/**
* Draws a square of side length 2r, centered on (x, y).
*
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws IllegalArgumentException if r is negative
*/
public void square(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("square side length can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a filled square of side length 2r, centered on (x, y).
*
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws IllegalArgumentException if r is negative
*/
public void filledSquare(double x, double y, double r) {
if (r < 0) throw new IllegalArgumentException("square side length can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a rectangle of given half width and half height, centered on (x, y).
*
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public void rectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) throw new IllegalArgumentException("half width can't be negative");
if (halfHeight < 0) throw new IllegalArgumentException("half height can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a filled rectangle of given half width and half height, centered on (x, y).
*
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth is half the width of the rectangle
* @param halfHeight is half the height of the rectangle
* @throws IllegalArgumentException if halfWidth or halfHeight is negative
*/
public void filledRectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) throw new IllegalArgumentException("half width can't be negative");
if (halfHeight < 0) throw new IllegalArgumentException("half height can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a polygon with the given (x[i], y[i]) coordinates.
*
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public void polygon(double[] x, double[] y) {
int n = x.length;
GeneralPath path = new GeneralPath();
path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < n; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.draw(path);
draw();
}
/**
* Draws a filled polygon with the given (x[i], y[i]) coordinates.
*
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public void filledPolygon(double[] x, double[] y) {
int n = x.length;
GeneralPath path = new GeneralPath();
path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < n; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.fill(path);
draw();
}
/***************************************************************************
* Drawing images.
***************************************************************************/
private static BufferedImage getImage(String filename) {
// from a file or URL
try {
URL url = new URL(filename);
return ImageIO.read(url);
}
catch (IOException e) {
// ignore
}
// in case file is inside a .jar (classpath relative to StdDraw)
try {
URL url = StdDraw.class.getResource(filename);
return ImageIO.read(url);
}
catch (IOException e) {
// ignore
}
// in case file is inside a .jar (classpath relative to root of jar)
try {
URL url = StdDraw.class.getResource("/" + filename);
return ImageIO.read(url);
}
catch (IOException e) {
// ignore
}
throw new IllegalArgumentException("image " + filename + " not found");
}
/**
* Draws picture (gif, jpg, or png) centered on (x, y).
*
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @throws IllegalArgumentException if the image is corrupt
* @throws IllegalArgumentException if {@code filename} is {@code null}
*/
public void picture(double x, double y, String filename) {
if (filename == null) throw new IllegalArgumentException("filename argument is null");
BufferedImage image = getImage(filename);
double xs = scaleX(x);
double ys = scaleY(y);
int ws = image.getWidth();
int hs = image.getHeight();
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);
draw();
}
/**
* Draws picture (gif, jpg, or png) centered on (x, y),
* rotated given number of degrees.
*
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @param degrees is the number of degrees to rotate counterclockwise
* @throws IllegalArgumentException if the image is corrupt
* @throws IllegalArgumentException if {@code filename} is {@code null}
*/
public void picture(double x, double y, String filename, double degrees) {
if (filename == null) throw new IllegalArgumentException("filename argument is null");
BufferedImage image = getImage(filename);
double xs = scaleX(x);
double ys = scaleY(y);
int ws = image.getWidth();
int hs = image.getHeight();
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
draw();
}
/**
* Draws picture (gif, jpg, or png) centered on (x, y), rescaled to w-by-h.
*
* @param x the center x coordinate of the image
* @param y the center y coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @param w the width of the image
* @param h the height of the image
* @throws IllegalArgumentException if the image is corrupt
* @throws IllegalArgumentException if {@code filename} is {@code null}
*/
public void picture(double x, double y, String filename, double w, double h) {
if (filename == null) throw new IllegalArgumentException("filename argument is null");
Image image = getImage(filename);
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(w);
double hs = factorY(h);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
else {
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),
(int) Math.round(ys - hs/2.0),
(int) Math.round(ws),
(int) Math.round(hs), null);
}
draw();
}
/**
* Draws picture (gif, jpg, or png) centered on (x, y), rotated
* given number of degrees, rescaled to w-by-h.
*
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @param w the width of the image
* @param h the height of the image
* @param degrees is the number of degrees to rotate counterclockwise
* @throws IllegalArgumentException if the image is corrupt
* @throws IllegalArgumentException if {@code filename} is {@code null}
*/
public void picture(double x, double y, String filename, double w, double h, double degrees) {
if (filename == null) throw new IllegalArgumentException("filename argument is null");
Image image = getImage(filename);
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(w);
double hs = factorY(h);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),
(int) Math.round(ys - hs/2.0),
(int) Math.round(ws),
(int) Math.round(hs), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
draw();
}
/***************************************************************************
* Drawing text.
***************************************************************************/
/**
* Writes the given text string in the current font, centered on (x, y).
*
* @param x the center x-coordinate of the text
* @param y the center y-coordinate of the text
* @param s the text
*/
public void text(double x, double y, String s) {
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
int ws = metrics.stringWidth(s);
int hs = metrics.getDescent();
offscreen.drawString(s, (float) (xs - ws/2.0), (float) (ys + hs));
draw();
}
/**
* Writes the given text string in the current font, centered on (x, y) and
* rotated by the specified number of degrees.
*
* @param x the center x-coordinate of the text
* @param y the center y-coordinate of the text
* @param s the text
* @param degrees is the number of degrees to rotate counterclockwise
*/
public void text(double x, double y, String s, double degrees) {
double xs = scaleX(x);
double ys = scaleY(y);
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
text(x, y, s);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
}
/**
* Writes the given text string in the current font, left-aligned at (x, y).
*
* @param x the x-coordinate of the text
* @param y the y-coordinate of the text
* @param s the text
*/
public void textLeft(double x, double y, String s) {
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
// int ws = metrics.stringWidth(s);
int hs = metrics.getDescent();
offscreen.drawString(s, (float) xs, (float) (ys + hs));
draw();
}
/**
* Displays on screen, pause for {@code t} milliseconds, and turn on
* <em>animation mode</em>.
* Subsequent calls to drawing methods such as {@code line()}, {@code circle()},
* and {@code square()} will not be displayed on screen until the next call to {@code show()}.
* This is useful for producing animations (clear the screen, draw a bunch of shapes,
* display on screen for a fixed amount of time, and repeat). It also speeds up
* drawing a huge number of shapes (call {@code show(0)} to defer drawing
* on screen, draw the shapes, and call {@code show(0)} to display them all
* on screen at once).
*
* @param t number of milliseconds
*/
public void show(int t) {
defer = false;
draw();
try {
Thread.sleep(t);
}
catch (InterruptedException e) {
System.out.println("Error sleeping");
}
defer = true;
}
/**
* Displays on-screen and turn off animation mode.
* Subsequent calls to drawing methods such as {@code line()}, {@code circle()},
* and {@code square()} will be displayed on screen when called. This is the default.
*/
public void show() {
defer = false;
draw();
}
// draw onscreen if defer is false
private void draw() {
if (defer) return;
onscreen.drawImage(offscreenImage, 0, 0, null);
frame.repaint();
}
/**
* Saves this drawing to a file.
*
* @param filename the name of the file (with suffix png, jpg, or gif)
*/
public void save(String filename) {
File file = new File(filename);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
// png files
if ("png".equalsIgnoreCase(suffix)) {
try {
ImageIO.write(offscreenImage, suffix, file);
}
catch (IOException e) {
e.printStackTrace();
}
}
// need to change from ARGB to RGB for jpeg
// reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
else if ("jpg".equalsIgnoreCase(suffix)) {
WritableRaster raster = offscreenImage.getRaster();
WritableRaster newRaster;
newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
DirectColorModel cm = (DirectColorModel) offscreenImage.getColorModel();
DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
cm.getRedMask(),
cm.getGreenMask(),
cm.getBlueMask());
BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
try {
ImageIO.write(rgbBuffer, suffix, file);
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
System.out.println("Invalid image file type: " + suffix);
}
}
/**
* This method cannot be called directly.
*/
@Override
public void actionPerformed(ActionEvent e) {
FileDialog chooser = new FileDialog(frame, "Use a .png or .jpg extension", FileDialog.SAVE);
chooser.setVisible(true);
String filename = chooser.getFile();
if (filename != null) {
save(chooser.getDirectory() + File.separator + chooser.getFile());
}
}
/***************************************************************************
* Event-based interactions.
***************************************************************************/
/**
* Adds a {@link DrawListener} to listen to keyboard and mouse events.
*
* @param listener the {\tt DrawListener} argument
*/
public void addListener(DrawListener listener) {
// ensure there is a window for listenting to events
show();
listeners.add(listener);
frame.addKeyListener(this);
frame.addMouseListener(this);
frame.addMouseMotionListener(this);
frame.setFocusable(true);
}
/***************************************************************************
* Mouse interactions.
***************************************************************************/
/**
* Returns true if the mouse is being pressed.
*
* @return {@code true} if the mouse is being pressed;
* {@code false} otherwise
*/
public boolean mousePressed() {
synchronized (mouseLock) {
return mousePressed;
}
}
/**
* Returns the x-coordinate of the mouse.
* @return the x-coordinate of the mouse
*/
public double mouseX() {
synchronized (mouseLock) {
return mouseX;
}
}
/**
* Returns the y-coordinate of the mouse.
*
* @return the y-coordinate of the mouse
*/
public double mouseY() {
synchronized (mouseLock) {
return mouseY;
}
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseClicked(MouseEvent e) {
// this body is intentionally left empty
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseEntered(MouseEvent e) {
// this body is intentionally left empty
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseExited(MouseEvent e) {
// this body is intentionally left empty
}
/**
* This method cannot be called directly.
*/
@Override
public void mousePressed(MouseEvent e) {
synchronized (mouseLock) {
mouseX = userX(e.getX());
mouseY = userY(e.getY());
mousePressed = true;
}
if (e.getButton() == MouseEvent.BUTTON1) {
for (DrawListener listener : listeners)
listener.mousePressed(userX(e.getX()), userY(e.getY()));
}
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseReleased(MouseEvent e) {
synchronized (mouseLock) {
mousePressed = false;
}
if (e.getButton() == MouseEvent.BUTTON1) {
for (DrawListener listener : listeners)
listener.mouseReleased(userX(e.getX()), userY(e.getY()));
}
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseDragged(MouseEvent e) {
synchronized (mouseLock) {
mouseX = userX(e.getX());
mouseY = userY(e.getY());
}
// doesn't seem to work if a button is specified
for (DrawListener listener : listeners)
listener.mouseDragged(userX(e.getX()), userY(e.getY()));
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseMoved(MouseEvent e) {
synchronized (mouseLock) {
mouseX = userX(e.getX());
mouseY = userY(e.getY());
}
}
/***************************************************************************
* Keyboard interactions.
***************************************************************************/
/**
* Returns true if the user has typed a key.
*
* @return {@code true} if the user has typed a key; {@code false} otherwise
*/
public boolean hasNextKeyTyped() {
synchronized (keyLock) {
return !keysTyped.isEmpty();
}
}
/**
* The next key typed by the user.
*
* @return the next key typed by the user
*/
public char nextKeyTyped() {
synchronized (keyLock) {
return keysTyped.removeLast();
}
}
/**
* Returns true if the keycode is being pressed.
* <p>
* This method takes as an argument the keycode (corresponding to a physical key).
* It can handle action keys (such as F1 and arrow keys) and modifier keys
* (such as shift and control).
* See {@link KeyEvent} for a description of key codes.
*
* @param keycode the keycode to check
* @return {@code true} if {@code keycode} is currently being pressed;
* {@code false} otherwise
*/
public boolean isKeyPressed(int keycode) {
synchronized (keyLock) {
return keysDown.contains(keycode);
}
}
/**
* This method cannot be called directly.
*/
@Override
public void keyTyped(KeyEvent e) {
synchronized (keyLock) {
keysTyped.addFirst(e.getKeyChar());
}
// notify all listeners
for (DrawListener listener : listeners)
listener.keyTyped(e.getKeyChar());
}
/**
* This method cannot be called directly.
*/
@Override
public void keyPressed(KeyEvent e) {
synchronized (keyLock) {
keysDown.add(e.getKeyCode());
}
// notify all listeners
for (DrawListener listener : listeners)
listener.keyPressed(e.getKeyCode());
}
/**
* This method cannot be called directly.
*/
@Override
public void keyReleased(KeyEvent e) {
synchronized (keyLock) {
keysDown.remove(e.getKeyCode());
}
// notify all listeners
for (DrawListener listener : listeners)
listener.keyPressed(e.getKeyCode());
}
/**
* Test client.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// create one drawing window
Draw draw1 = new Draw("Test client 1");
draw1.square(.2, .8, .1);
draw1.filledSquare(.8, .8, .2);
draw1.circle(.8, .2, .2);
draw1.setPenColor(Draw.MAGENTA);
draw1.setPenRadius(.02);
draw1.arc(.8, .2, .1, 200, 45);
// create another one
Draw draw2 = new Draw("Test client 2");
draw2.setCanvasSize(900, 200);
// draw a blue diamond
draw2.setPenRadius();
draw2.setPenColor(Draw.BLUE);
double[] x = { .1, .2, .3, .2 };
double[] y = { .2, .3, .2, .1 };
draw2.filledPolygon(x, y);
// text
draw2.setPenColor(Draw.BLACK);
draw2.text(0.2, 0.5, "bdfdfdfdlack text");
draw2.setPenColor(Draw.WHITE);
draw2.text(0.8, 0.8, "white text");
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/DrawListener.java
================================================
/******************************************************************************
* Compilation: javac DrawListener.java
* Execution: none
* Dependencies: none
*
* Interface that accompanies Draw.java.
******************************************************************************/
package algs4;
public interface DrawListener {
/**
* Invoked when the mouse has been pressed.
*
* @param x the x-coordinate of the mouse
* @param y the y-coordinate of the mouse
*/
void mousePressed(double x, double y);
/**
* Invoked when the mouse has been dragged.
*
* @param x the x-coordinate of the mouse
* @param y the y-coordinate of the mouse
*/
void mouseDragged(double x, double y);
/**
* Invoked when the mouse has been released.
*
* @param x the x-coordinate of the mouse
* @param y the y-coordinate of the mouse
*/
void mouseReleased(double x, double y);
/**
* Invoked when a key has been typed.
*
* @param c the character typed
*/
void keyTyped(char c);
/**
* Invoked when a key has been pressed.
*
* @param keycode the key combination pressed
*/
void keyPressed(int keycode);
/**
* Invoked when a key has been released.
*
* @param keycode the key combination released
*/
void keyReleased(int keycode);
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Heap.java
================================================
/******************************************************************************
* Compilation: javac Heap.java
* Execution: java Heap < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/24pq/tiny.txt
* http://algs4.cs.princeton.edu/24pq/words3.txt
*
* Sorts a sequence of strings from standard input using heapsort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Heap < 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 Heap < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
package algs4;
/**
* The {@code Heap} class provides a static methods for heapsorting
* an array.
* <p>
* For additional documentation, see <a href="http://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
*/
public class Heap {
// This class should not be instantiated.
private Heap() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param pq the array to be sorted
*/
public static void sort(Comparable[] pq) {
int n = pq.length;
for (int k = n/2; k >= 1; k--)
sink(pq, k, n);
while (n > 1) {
exch(pq, 1, n--);
sink(pq, 1, n);
}
}
/***************************************************************************
* Helper functions to restore the heap invariant.
***************************************************************************/
private static void sink(Comparable[] pq, int k, int n) {
while (2*k <= n) {
int j = 2*k;
if (j < n && less(pq, j, j+1)) j++;
if (!less(pq, k, j)) break;
exch(pq, k, j);
k = j;
}
}
/***************************************************************************
* Helper functions for comparisons and swaps.
* Indices are "off-by-one" to support 1-based indexing.
***************************************************************************/
private static boolean less(Comparable[] pq, int i, int j) {
return pq[i-1].compareTo(pq[j-1]) < 0;
}
private static void exch(Object[] pq, int i, int j) {
Object swap = pq[i-1];
pq[i-1] = pq[j-1];
pq[j-1] = swap;
}
// 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) {
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; heapsorts 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();
Heap.sort(a);
show(a);
assert isSorted(a);
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/HexDump.java
================================================
/******************************************************************************
* Compilation: javac HexDump.java
* Execution: java HexDump < file
* Dependencies: BinaryStdIn.java StdOut.java
* Data file: http://algs4.cs.princeton.edu/55compression/abra.txt
*
* Reads in a binary file and writes out the bytes in hex, 16 per line.
*
* % more abra.txt
* ABRACADABRA!
*
* % java HexDump 16 < abra.txt
* 41 42 52 41 43 41 44 41 42 52 41 21
* 96 bits
*
*
* Remark
* --------------------------
* - Similar to the Unix utilities od (octal dump) or hexdump (hexadecimal dump).
*
* % od -t x1 < abra.txt
* 0000000 41 42 52 41 43 41 44 41 42 52 41 21
* 0000014
*
******************************************************************************/
package algs4;
/**
* The {@code HexDump} class provides a client for displaying the contents
* of a binary file in hexadecimal.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/55compress">Section 5.5</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* <p>
* See also {@link BinaryDump} and {@link PictureDump}.
* For more full-featured versions, see the Unix utilities
* {@code od} (octal dump) and {@code hexdump} (hexadecimal dump).
* <p>
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class HexDump {
// Do not instantiate.
private HexDump() { }
/**
* Reads in a sequence of bytes from standard input and writes
* them to standard output using hexademical notation, k hex digits
* per line, where k is given as a command-line integer (defaults
* to 16 if no integer is specified); also writes the number
* of bits.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int bytesPerLine = 16;
if (args.length == 1) {
bytesPerLine = Integer.parseInt(args[0]);
}
int i;
for (i = 0; !BinaryStdIn.isEmpty(); i++) {
if (bytesPerLine == 0) {
BinaryStdIn.readChar();
continue;
}
if (i == 0) StdOut.printf("");
else if (i % bytesPerLine == 0) StdOut.printf("\n", i);
else StdOut.print(" ");
char c = BinaryStdIn.readChar();
StdOut.printf("%02x", c & 0xff);
}
if (bytesPerLine != 0) StdOut.println();
StdOut.println((i*8) + " bits");
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/In.java
================================================
/******************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
* Dependencies: none
*
* Reads in data of various types from standard input, files, and URLs.
*
******************************************************************************/
package algs4;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.Socket;
// import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Computer Science: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In {
///// begin: section (1 of 2) of code duplicated from In to StdIn.
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
//// end: section (1 of 2) of code duplicated from In to StdIn.
private Scanner scanner;
/**
* Initializes an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
/**
* Initializes an input stream from a socket.
*
* @param socket the socket
* @throws IllegalArgumentException if cannot open {@code socket}
* @throws IllegalArgumentException if {@code socket} is {@code null}
*/
public In(Socket socket) {
if (socket == null) throw new IllegalArgumentException("socket argument is null");
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + socket, ioe);
}
}
/**
* Initializes an input stream from a URL.
*
* @param url the URL
* @throws IllegalArgumentException if cannot open {@code url}
* @throws IllegalArgumentException if {@code url} is {@code null}
*/
public In(URL url) {
if (url == null) throw new IllegalArgumentException("url argument is null");
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + url, ioe);
}
}
/**
* Initializes an input stream from a file.
*
* @param file the file
* @throws IllegalArgumentException if cannot open {@code file}
* @throws IllegalArgumentException if {@code file} is {@code null}
*/
public In(File file) {
if (file == null) throw new IllegalArgumentException("file argument is null");
try {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + file, ioe);
}
}
/**
* Initializes an input stream from a filename or web page name.
*
* @param name the filename or web page name
* @throws IllegalArgumentException if cannot open {@code name} as
* a file or URL
* @throws IllegalArgumentException if {@code name} is {@code null}
*/
public In(String name) {
if (name == null) throw new IllegalArgumentException("argument is null");
try {
// first try to read file from local file system
File file = new File(name);
if (file.exists()) {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
return;
}
// next try for files included in jar
URL url = getClass().getResource(name);
// or URL from web
if (url == null) {
url = new URL(name);
}
URLConnection site = url.openConnection();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + name, ioe);
}
}
/**
* Initializes an input stream from a given {@link Scanner} source; use with
* {@code new Scanner(String)} to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*
* @param scanner the scanner
* @throws IllegalArgumentException if {@code scanner} is {@code null}
*/
public In(Scanner scanner) {
if (scanner == null) throw new IllegalArgumentException("scanner argument is null");
this.scanner = scanner;
}
/**
* Returns true if this input stream exists.
*
* @return {@code true} if this input stream exists; {@code false} otherwise
*/
public boolean exists() {
return scanner != null;
}
//// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static".
/**
* Returns true if input stream is empty (except possibly whitespace).
* Use this to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return {@code true} if this input stream is empty (except possibly whitespace);
* {@code false} otherwise
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Returns true if this input stream has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return {@code true} if this input stream has more input (including whitespace);
* {@code false} otherwise
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Returns true if this input stream has more inputy (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return {@code true} if this input stream has more input (including whitespace);
* {@code false} otherwise
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Reads and returns the next line in this input stream.
*
* @return the next line in this input stream; {@code null} if no such line
*/
public String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
}
/**
* Reads and returns the next character in this input stream.
*
* @return the next character in this input stream
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Reads and returns the remainder of this input stream, as a string.
*
* @return the remainder of this input stream, as a string
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Reads the next token from this input stream and returns it as a {@code String}.
*
* @return the next {@code String} in this input stream
*/
public String readString() {
return scanner.next();
}
/**
* Reads the next token from this input stream, parses it as a {@code int},
* and returns the {@code int}.
*
* @return the next {@code int} in this input stream
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Reads the next token from this input stream, parses it as a {@code double},
* and returns the {@code double}.
*
* @return the next {@code double} in this input stream
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Reads the next token from this input stream, parses it as a {@code float},
* and returns the {@code float}.
*
* @return the next {@code float} in this input stream
*/
public float readFloat() {
return scanner.nextFloat();
}
/**
* Reads the next token from this input stream, parses it as a {@code long},
* and returns the {@code long}.
*
* @return the next {@code long} in this input stream
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Reads the next token from this input stream, parses it as a {@code short},
* and returns the {@code short}.
*
* @return the next {@code short} in this input stream
*/
public short readShort() {
return scanner.nextShort();
}
/**
* Reads the next token from this input stream, parses it as a {@code byte},
* and returns the {@code byte}.
* <p>
* To read binary data, use {@link BinaryIn}.
*
* @return the next {@code byte} in this input stream
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Reads the next token from this input stream, parses it as a {@code boolean}
* (interpreting either {@code "true"} or {@code "1"} as {@code true},
* and either {@code "false"} or {@code "0"} as {@code false}).
*
* @return the next {@code boolean} in this input stream
*/
public boolean readBoolean() {
String s = readString();
if ("true".equalsIgnoreCase(s)) return true;
if ("false".equalsIgnoreCase(s)) return false;
if ("1".equals(s)) return true;
if ("0".equals(s)) return false;
throw new InputMismatchException();
}
/**
* Reads all remaining tokens from this input stream and returns them as
* an array of strings.
*
* @return all remaining tokens in this input stream, as an array of strings
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from this input stream and returns them as
* an array of strings.
*
* @return all remaining lines in this input stream, as an array of strings
*/
public String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[lines.size()]);
}
/**
* Reads all remaining tokens from this input stream, parses them as integers,
* and returns them as an array of integers.
*
* @return all remaining lines in this input stream, as an array of integers
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from this input stream, parses them as longs,
* and returns them as an array of longs.
*
* @return all remaining lines in this input stream, as an array of longs
*/
public long[] readAllLongs() {
String[] fields = readAllStrings();
long[] vals = new long[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Long.parseLong(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from this input stream, parses them as doubles,
* and returns them as an array of doubles.
*
* @return all remaining lines in this input stream, as an array of doubles
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
///// end: section (2 of 2) of code duplicated from In to StdIn */
/**
* Closes this input stream.
*/
public void close() {
scanner.close();
}
/**
* Reads all integers from a file and returns them as
* an array of integers.
*
* @param filename the name of the file
* @return the integers in the file
* @deprecated Replaced by {@code new In(filename)}.{@link #readAllInts()}.
*/
@Deprecated
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
}
/**
* Reads all doubles from a file and returns them as
* an array of doubles.
*
* @param filename the name of the file
* @return the doubles in the file
* @deprecated Replaced by {@code new In(filename)}.{@link #readAllDoubles()}.
*/
@Deprecated
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
}
/**
* Reads all strings from a file and returns them as
* an array of strings.
*
* @param filename the name of the file
* @return the strings in the file
* @deprecated Replaced by {@code new In(filename)}.{@link #readAllStrings()}.
*/
@Deprecated
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
}
/**
* Reads all integers from standard input and returns them
* an array of integers.
*
* @return the integers on standard input
* @deprecated Replaced by {@link StdIn#readAllInts()}.
*/
@Deprecated
public static int[] readInts() {
return new In().readAllInts();
}
/**
* Reads all doubles from standard input and returns them as
* an array of doubles.
*
* @return the doubles on standard input
* @deprecated Replaced by {@link StdIn#readAllDoubles()}.
*/
@Deprecated
public static double[] readDoubles() {
return new In().readAllDoubles();
}
/**
* Reads all strings from standard input and returns them as
* an array of strings.
*
* @return the strings on standard input
* @deprecated Replaced by {@link StdIn#readAllStrings()}.
*/
@Deprecated
public static String[] readStrings() {
return new In().readAllStrings();
}
/**
* Unit tests the {@code In} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/IndexMinPQ.java
================================================
/******************************************************************************
* Compilation: javac IndexMinPQ.java
* Execution: java IndexMinPQ
* Dependencies: StdOut.java
*
* Minimum-oriented indexed PQ implementation using a binary heap.
*
******************************************************************************/
package algs4;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code IndexMinPQ} class represents an indexed priority queue of generic keys.
* It supports the usual <em>insert</em> and <em>delete-the-minimum</em>
* operations, along with <em>delete</em> and <em>change-the-key</em>
* methods. In order to let the client refer to keys on the priority queue,
* an integer between {@code 0} and {@code maxN - 1}
* is associated with each key—the client uses this integer to specify
* which key to delete or change.
* It also supports methods for peeking at the minimum key,
* testing if the priority queue is empty, and iterating through
* the keys.
* <p>
* This implementation uses a binary heap along with an array to associate
* keys with integers in the given range.
* The <em>insert</em>, <em>delete-the-minimum</em>, <em>delete</em>,
* <em>change-key</em>, <em>decrease-key</em>, and <em>increase-key</em>
* operations take logarithmic time.
* The <em>is-empty</em>, <em>size</em>, <em>min-index</em>, <em>min-key</em>,
* and <em>key-of</em> operations take constant time.
* Construction takes time proportional to the specified capacity.
* <p>
* For additional documentation, see <a href="http://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 IndexMinPQ<Key extends Comparable<Key>> implements Iterable<Integer> {
private int maxN; // maximum number of elements on PQ
private int n; // number of elements on PQ
private int[] pq; // binary heap using 1-based indexing
private int[] qp; // inverse of pq - qp[pq[i]] = pq[qp[i]] = i
private Key[] keys; // keys[i] = priority of i
/**
* Initializes an empty indexed priority queue with indices between {@code 0}
* and {@code maxN - 1}.
* @param maxN the keys on this priority queue are index from {@code 0}
* {@code maxN - 1}
* @throws IllegalArgumentException if {@code maxN < 0}
*/
public IndexMinPQ(int maxN) {
if (maxN < 0) throw new IllegalArgumentException();
this.maxN = maxN;
n = 0;
keys = (Key[]) new Comparable[maxN + 1]; // make this of length maxN??
pq = new int[maxN + 1];
qp = new int[maxN + 1]; // make this of length maxN??
for (int i = 0; i <= maxN; i++)
qp[i] = -1;
}
/**
* 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;
}
/**
* Is {@code i} an index on this priority queue?
*
* @param i an index
* @return {@code true} if {@code i} is an index on this priority queue;
* {@code false} otherwise
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
*/
public boolean contains(int i) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
return qp[i] != -1;
}
/**
* Returns the number of keys on this priority queue.
*
* @return the number of keys on this priority queue
*/
public int size() {
return n;
}
/**
* Associates key with index {@code i}.
*
* @param i an index
* @param key the key to associate with index {@code i}
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
* @throws IllegalArgumentException if there already is an item associated
* with index {@code i}
*/
public void insert(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");
n++;
qp[i] = n;
pq[n] = i;
keys[i] = key;
swim(n);
}
/**
* Returns an index associated with a minimum key.
*
* @return an index associated with a minimum key
* @throws NoSuchElementException if this priority queue is empty
*/
public int minIndex() {
if (n == 0) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
/**
* Returns a minimum key.
*
* @return a minimum key
* @throws NoSuchElementException if this priority queue is empty
*/
public Key minKey() {
if (n == 0) throw new NoSuchElementException("Priority queue underflow");
return keys[pq[1]];
}
/**
* Removes a minimum key and returns its associated index.
* @return an index associated with a minimum key
* @throws NoSuchElementException if this priority queue is empty
*/
public int delMin() {
if (n == 0) throw new NoSuchElementException("Priority queue underflow");
int min = pq[1];
exch(1, n--);
sink(1);
assert min == pq[n+1];
qp[min] = -1; // delete
keys[min] = null; // to help with garbage collection
pq[n+1] = -1; // not needed
return min;
}
/**
* Returns the key associated with index {@code i}.
*
* @param i the index of the key to return
* @return the key associated with index {@code i}
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
* @throws NoSuchElementException no key is associated with index {@code i}
*/
public Key keyOf(int i) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
else return keys[i];
}
/**
* Change the key associated with index {@code i} to the specified value.
*
* @param i the index of the key to change
* @param key change the key associated with index {@code i} to this key
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
* @throws NoSuchElementException no key is associated with index {@code i}
*/
public void changeKey(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
keys[i] = key;
swim(qp[i]);
sink(qp[i]);
}
/**
* Change the key associated with index {@code i} to the specified value.
*
* @param i the index of the key to change
* @param key change the key associated with index {@code i} to this key
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
* @deprecated Replaced by {@code changeKey(int, Key)}.
*/
@Deprecated
public void change(int i, Key key) {
changeKey(i, key);
}
/**
* Decrease the key associated with index {@code i} to the specified value.
*
* @param i the index of the key to decrease
* @param key decrease the key associated with index {@code i} to this key
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
* @throws IllegalArgumentException if {@code key >= keyOf(i)}
* @throws NoSuchElementException no key is associated with index {@code i}
*/
public void decreaseKey(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) <= 0)
throw new IllegalArgumentException("Calling decreaseKey() with given argument would not strictly decrease the key");
keys[i] = key;
swim(qp[i]);
}
/**
* Increase the key associated with index {@code i} to the specified value.
*
* @param i the index of the key to increase
* @param key increase the key associated with index {@code i} to this key
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
* @throws IllegalArgumentException if {@code key <= keyOf(i)}
* @throws NoSuchElementException no key is associated with index {@code i}
*/
public void increaseKey(int i, Key key) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) >= 0)
throw new IllegalArgumentException("Calling increaseKey() with given argument would not strictly increase the key");
keys[i] = key;
sink(qp[i]);
}
/**
* Remove the key associated with index {@code i}.
*
* @param i the index of the key to remove
* @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}
* @throws NoSuchElementException no key is associated with index {@code i}
*/
public void delete(int i) {
if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
int index = qp[i];
exch(index, n--);
swim(index);
sink(index);
keys[i] = null;
qp[i] = -1;
}
/***************************************************************************
* General helper functions.
***************************************************************************/
private boolean greater(int i, int j) {
return keys[pq[i]].compareTo(keys[pq[j]]) > 0;
}
private void exch(int i, int j) {
int swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
qp[pq[i]] = i;
qp[pq[j]] = j;
}
/***************************************************************************
* Heap helper functions.
***************************************************************************/
private void swim(int k) {
while (k > 1 && greater(k/2, k)) {
exch(k, k/2);
k = k/2;
}
}
private void sink(int k) {
while (2*k <= n) {
int j = 2*k;
if (j < n && greater(j, j+1)) j++;
if (!greater(k, j)) break;
exch(k, j);
k = j;
}
}
/***************************************************************************
* Iterators.
***************************************************************************/
/**
* Returns an iterator that iterates over the keys on the
* priority queue in ascending order.
* The iterator doesn't implement {@code remove()} since it's optional.
*
* @return an iterator that iterates over the keys in ascending order
*/
public Iterator<Integer> iterator() { return new HeapIterator(); }
private class HeapIterator implements Iterator<Integer> {
// create a new pq
private IndexMinPQ<Key> copy;
// add all elements to copy of heap
// takes linear time since already in heap order so no keys move
public HeapIterator() {
copy = new IndexMinPQ<Key>(pq.length - 1);
for (int i = 1; i <= n; i++)
copy.insert(pq[i], keys[pq[i]]);
}
public boolean hasNext() { return !copy.isEmpty(); }
public void remove() { throw new UnsupportedOperationException(); }
public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return copy.delMin();
}
}
/**
* Unit tests the {@code IndexMinPQ} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// insert a bunch of strings
String[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" };
IndexMinPQ<String> pq = new IndexMinPQ<String>(strings.length);
for (int i = 0; i < strings.length; i++) {
pq.insert(i, strings[i]);
}
// delete and print each key
while (!pq.isEmpty()) {
int i = pq.delMin();
StdOut.println(i + " " + strings[i]);
}
StdOut.println();
// reinsert the same strings
for (int i = 0; i < strings.length; i++) {
pq.insert(i, strings[i]);
}
// print each key using the iterator
for (int i : pq) {
StdOut.println(i + " " + strings[i]);
}
while (!pq.isEmpty()) {
pq.delMin();
}
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Interval1D.java
================================================
/******************************************************************************
* Compilation: javac Interval1D.java
* Execution: java Interval1D
* Dependencies: StdOut.java
*
* 1-dimensional interval data type.
*
******************************************************************************/
package algs4;
import java.util.Arrays;
import java.util.Comparator;
/**
* The {@code Interval1D} class represents a one-dimensional interval.
* The interval is <em>closed</em>—it contains both endpoints.
* Intervals are immutable: their values cannot be changed after they are created.
* The class {@code Interval1D} includes methods for checking whether
* an interval contains a point and determining whether two intervals intersect.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/12oop">Section 1.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Interval1D {
/**
* Compares two intervals by min endpoint.
*/
public static final Comparator<Interval1D> MIN_ENDPOINT_ORDER = new MinEndpointComparator();
/**
* Compares two intervals by max endpoint.
*/
public static final Comparator<Interval1D> MAX_ENDPOINT_ORDER = new MaxEndpointComparator();
/**
* Compares two intervals by length.
*/
public static final Comparator<Interval1D> LENGTH_ORDER = new LengthComparator();
private final double min;
private final double max;
/**
* Initializes a closed interval [min, max].
*
* @param min the smaller endpoint
* @param max the larger endpoint
* @throws IllegalArgumentException if the min endpoint is greater than the max endpoint
* @throws IllegalArgumentException if either {@code min} or {@code max}
* is {@code Double.NaN}, {@code Double.POSITIVE_INFINITY} or
* {@code Double.NEGATIVE_INFINITY}
*/
public Interval1D(double min, double max) {
if (Double.isInfinite(min) || Double.isInfinite(max))
throw new IllegalArgumentException("Endpoints must be finite");
if (Double.isNaN(min) || Double.isNaN(max))
throw new IllegalArgumentException("Endpoints cannot be NaN");
// convert -0.0 to +0.0
if (min == 0.0) min = 0.0;
if (max == 0.0) max = 0.0;
if (min <= max) {
this.min = min;
this.max = max;
}
else throw new IllegalArgumentException("Illegal interval");
}
/**
* Returns the left endpoint of this interval.
*
* @return the left endpoint of this interval
* @deprecated Replaced by {@link #min()}.
*/
@Deprecated
public double left() {
return min;
}
/**
* Returns the right endpoint of this interval.
* @return the right endpoint of this interval
* @deprecated Replaced by {@link #max()}.
*/
@Deprecated
public double right() {
return max;
}
/**
* Returns the min endpoint of this interval.
*
* @return the min endpoint of this interval
*/
public double min() {
return min;
}
/**
* Returns the max endpoint of this interval.
*
* @return the max endpoint of this interval
*/
public double max() {
return max;
}
/**
* Returns true if this interval intersects the specified interval.
*
* @param that the other interval
* @return {@code true} if this interval intersects the argument interval;
* {@code false} otherwise
*/
public boolean intersects(Interval1D that) {
if (this.max < that.min) return false;
if (that.max < this.min) return false;
return true;
}
/**
* Returns true if this interval contains the specified value.
*
* @param x the value
* @return {@code true} if this interval contains the value {@code x};
* {@code false} otherwise
*/
public boolean contains(double x) {
return (min <= x) && (x <= max);
}
/**
* Returns the length of this interval.
*
* @return the length of this interval (max - min)
*/
public double length() {
return max - min;
}
/**
* Returns a string representation of this interval.
*
* @return a string representation of this interval in the form [min, max]
*/
public String toString() {
return "[" + min + ", " + max + "]";
}
/**
* Compares this transaction to the specified object.
*
* @param other the other interval
* @return {@code true} if this interval equals the other interval;
* {@code false} otherwise
*/
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Interval1D that = (Interval1D) other;
return this.min == that.min && this.max == that.max;
}
/**
* Returns an integer hash code for this interval.
*
* @return an integer hash code for this interval
*/
public int hashCode() {
int hash1 = ((Double) min).hashCode();
int hash2 = ((Double) max).hashCode();
return 31*hash1 + hash2;
}
// ascending order of min endpoint, breaking ties by max endpoint
private static class MinEndpointComparator implements Comparator<Interval1D> {
public int compare(Interval1D a, Interval1D b) {
if (a.min < b.min) return -1;
else if (a.min > b.min) return +1;
else if (a.max < b.max) return -1;
else if (a.max > b.max) return +1;
else return 0;
}
}
// ascending order of max endpoint, breaking ties by min endpoint
private static class MaxEndpointComparator implements Comparator<Interval1D> {
public int compare(Interval1D a, Interval1D b) {
if (a.min < b.max) return -1;
else if (a.min > b.max) return +1;
else if (a.min < b.min) return -1;
else if (a.min > b.min) return +1;
else return 0;
}
}
// ascending order of length
private static class LengthComparator implements Comparator<Interval1D> {
public int compare(Interval1D a, Interval1D b) {
double alen = a.length();
double blen = b.length();
if (alen < blen) return -1;
else if (alen > blen) return +1;
else return 0;
}
}
/**
* Unit tests the {@code Interval1D} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Interval1D[] intervals = new Interval1D[4];
intervals[0] = new Interval1D(15.0, 33.0);
intervals[1] = new Interval1D(45.0, 60.0);
intervals[2] = new Interval1D(20.0, 70.0);
intervals[3] = new Interval1D(46.0, 55.0);
StdOut.println("Unsorted");
for (int i = 0; i < intervals.length; i++)
StdOut.println(intervals[i]);
StdOut.println();
StdOut.println("Sort by min endpoint");
Arrays.sort(intervals, Interval1D.MIN_ENDPOINT_ORDER);
for (int i = 0; i < intervals.length; i++)
StdOut.println(intervals[i]);
StdOut.println();
StdOut.println("Sort by max endpoint");
Arrays.sort(intervals, Interval1D.MAX_ENDPOINT_ORDER);
for (int i = 0; i < intervals.length; i++)
StdOut.println(intervals[i]);
StdOut.println();
StdOut.println("Sort by length");
Arrays.sort(intervals, Interval1D.LENGTH_ORDER);
for (int i = 0; i < intervals.length; i++)
StdOut.println(intervals[i]);
StdOut.println();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Interval2D.java
================================================
/******************************************************************************
* Compilation: javac Interval2D.java
* Execution: java Interval2D
* Dependencies: StdOut.java Interval1D.java StdDraw.java
*
* 2-dimensional interval data type.
*
******************************************************************************/
package algs4;
/**
* The {@code Interval2D} class represents a closed two-dimensional interval,
* which represents all points (x, y) with both {@code xmin <= x <= xmax} and
* {@code ymin <= y <= ymax}.
* Two-dimensional intervals are immutable: their values cannot be changed
* after they are created.
* The class {@code Interval2D} includes methods for checking whether
* a two-dimensional interval contains a point and determining whether
* two two-dimensional intervals intersect.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/12oop">Section 1.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Interval2D {
private final Interval1D x;
private final Interval1D y;
/**
* Initializes a two-dimensional interval.
* @param x the one-dimensional interval of x-coordinates
* @param y the one-dimensional interval of y-coordinates
*/
public Interval2D(Interval1D x, Interval1D y) {
this.x = x;
this.y = y;
}
/**
* Does this two-dimensional interval intersect that two-dimensional interval?
* @param that the other two-dimensional interval
* @return true if this two-dimensional interval intersects
* that two-dimensional interval; false otherwise
*/
public boolean intersects(Interval2D that) {
if (!this.x.intersects(that.x)) return false;
if (!this.y.intersects(that.y)) return false;
return true;
}
/**
* Does this two-dimensional interval contain the point p?
* @param p the two-dimensional point
* @return true if this two-dimensional interval contains the point p; false otherwise
*/
public boolean contains(Point2D p) {
return x.contains(p.x()) && y.contains(p.y());
}
/**
* Returns the area of this two-dimensional interval.
* @return the area of this two-dimensional interval
*/
public double area() {
return x.length() * y.length();
}
/**
* Returns a string representation of this two-dimensional interval.
* @return a string representation of this two-dimensional interval
* in the form [xmin, xmax] x [ymin, ymax]
*/
public String toString() {
return x + " x " + y;
}
/**
* Does this interval equal the other interval?
* @param other the other interval
* @return true if this interval equals the other interval; false otherwise
*/
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Interval2D that = (Interval2D) other;
return this.x.equals(that.x) && this.y.equals(that.y);
}
/**
* Returns an integer hash code for this interval.
* @return an integer hash code for this interval
*/
public int hashCode() {
int hash1 = x.hashCode();
int hash2 = y.hashCode();
return 31*hash1 + hash2;
}
/**
* Draws this two-dimensional interval to standard draw.
*/
public void draw() {
double xc = (x.min() + x.max()) / 2.0;
double yc = (y.min() + y.max()) / 2.0;
StdDraw.rectangle(xc, yc, x.length() / 2.0, y.length() / 2.0);
}
/**
* Unit tests the {@code Interval2D} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
double xmin = Double.parseDouble(args[0]);
double xmax = Double.parseDouble(args[1]);
double ymin = Double.parseDouble(args[2]);
double ymax = Double.parseDouble(args[3]);
int trials = Integer.parseInt(args[4]);
Interval1D xInterval = new Interval1D(xmin, xmax);
Interval1D yInterval = new Interval1D(ymin, ymax);
Interval2D box = new Interval2D(xInterval, yInterval);
box.draw();
Counter counter = new Counter("hits");
for (int t = 0; t < trials; t++) {
double x = StdRandom.uniform(0.0, 1.0);
double y = StdRandom.uniform(0.0, 1.0);
Point2D point = new Point2D(x, y);
if (box.contains(point)) counter.increment();
else point.draw();
}
StdOut.println(counter);
StdOut.printf("box area = %.2f\n", box.area());
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/MinPQ.java
================================================
/******************************************************************************
* Compilation: javac MinPQ.java
* Execution: java MinPQ < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/24pq/tinyPQ.txt
*
* Generic min priority queue implementation with a binary heap.
* Can be used with a comparator instead of the natural order.
*
* % java MinPQ < tinyPQ.txt
* E A E (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).
*
******************************************************************************/
package algs4;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code MinPQ} class represents a priority queue of generic keys.
* It supports the usual <em>insert</em> and <em>delete-the-minimum</em>
* operations, along with methods for peeking at the minimum key,
* testing if the priority queue is empty, and iterating through
* the keys.
* <p>
* This implementation uses a binary heap.
* The <em>insert</em> and <em>delete-the-minimum</em> operations take
* logarithmic amortized time.
* The <em>min</em>, <em>size</em>, and <em>is-empty</em> operations take constant time.
* 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="http://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 MinPQ<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 MinPQ(int initCapacity) {
pq = (Key[]) new Object[initCapacity + 1];
n = 0;
}
/**
* Initializes an empty priority queue.
*/
public MinPQ() {
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 to use when comparing keys
*/
public MinPQ(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 to use when comparing keys
*/
public MinPQ(Comparator<Key> comparator) {
this(1, comparator);
}
/**
* Initializes a priority queue from the array of keys.
* <p>
* Takes time proportional to the number of keys, using sink-based heap construction.
*
* @param keys the array of keys
*/
public MinPQ(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 isMinHeap();
}
/**
* 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 smallest key on this priority queue.
*
* @return a smallest key on this priority queue
* @throws NoSuchElementException if this priority queue is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
// helper function to double the size of the heap array
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 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 isMinHeap();
}
/**
* Removes and returns a smallest key on this priority queue.
*
* @return a smallest key on this priority queue
* @throws NoSuchElementException if this priority queue is empty
*/
public Key delMin() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
exch(1, n);
Key min = pq[n--];
sink(1);
pq[n+1] = null; // avoid loitering and help with garbage collection
if ((n > 0) && (n == (pq.length - 1) / 4)) resize(pq.length / 2);
assert isMinHeap();
return min;
}
/***************************************************************************
* Helper functions to restore the heap invariant.
***************************************************************************/
private void swim(int k) {
while (k > 1 && greater(k/2, k)) {
exch(k, k/2);
k = k/2;
}
}
private void sink(int k) {
while (2*k <= n) {
int j = 2*k;
if (j < n && greater(j, j+1)) j++;
if (!greater(k, j)) break;
exch(k, j);
k = j;
}
}
/***************************************************************************
* Helper functions for compares and swaps.
***************************************************************************/
private boolean greater(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 min heap?
private boolean isMinHeap() {
return isMinHeap(1);
}
// is subtree of pq[1..n] rooted at k a min heap?
private boolean isMinHeap(int k) {
if (k > n) return true;
int left = 2*k;
int right = 2*k + 1;
if (left <= n && greater(k, left)) return false;
if (right <= n && greater(k, right)) return false;
return isMinHeap(left) && isMinHeap(right);
}
/**
* Returns an iterator that iterates over the keys on this priority queue
* in ascending order.
* <p>
* The iterator doesn't implement {@code remove()} since it's optional.
*
* @return an iterator that iterates over the keys in ascending order
*/
public Iterator<Key> iterator() { return new HeapIterator(); }
private class HeapIterator implements Iterator<Key> {
// create a new pq
private MinPQ<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 MinPQ<Key>(size());
else copy = new MinPQ<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.delMin();
}
}
/**
* Unit tests the {@code MinPQ} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
MinPQ<String> pq = new MinPQ<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) pq.insert(item);
else if (!pq.isEmpty()) StdOut.print(pq.delMin() + " ");
}
StdOut.println("(" + pq.size() + " left on pq)");
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Out.java
================================================
/******************************************************************************
* Compilation: javac Out.java
* Execution: java Out
* Dependencies: none
*
* Writes data of various types to: stdout, file, or socket.
*
******************************************************************************/
package algs4;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Locale;
/**
* This class provides methods for writing strings and numbers to
* various output streams, including standard output, file, and sockets.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Computer Science: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Out {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with In
private static final Locale LOCALE = Locale.US;
private PrintWriter out;
/**
* Initializes an output stream from a {@link OutputStream}.
*
* @param os the {@code OutputStream}
*/
public Out(OutputStream os) {
try {
OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);
out = new PrintWriter(osw, true);
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initializes an output stream from standard output.
*/
public Out() {
this(System.out);
}
/**
* Initializes an output stream from a socket.
*
* @param socket the socket
*/
public Out(Socket socket) {
try {
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);
out = new PrintWriter(osw, true);
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initializes an output stream from a file.
*
* @param filename the name of the file
*/
public Out(String filename) {
try {
OutputStream os = new FileOutputStream(f
gitextract_vx5c0m3w/ ├── .gitignore ├── README.md ├── code/ │ ├── README.md │ ├── algs4/ │ │ ├── Alphabet.java │ │ ├── Bag.java │ │ ├── BinarySearch.java │ │ ├── BinaryStdIn.java │ │ ├── BinaryStdOut.java │ │ ├── Counter.java │ │ ├── DepthFirstOrder.java │ │ ├── Draw.java │ │ ├── DrawListener.java │ │ ├── Heap.java │ │ ├── HexDump.java │ │ ├── In.java │ │ ├── IndexMinPQ.java │ │ ├── Interval1D.java │ │ ├── Interval2D.java │ │ ├── MinPQ.java │ │ ├── Out.java │ │ ├── Particle.java │ │ ├── Picture.java │ │ ├── PictureDump.java │ │ ├── Point2D.java │ │ ├── Queue.java │ │ ├── SET.java │ │ ├── ST.java │ │ ├── Stack.java │ │ ├── StdDraw.java │ │ ├── StdIn.java │ │ ├── StdOut.java │ │ └── StdRandom.java │ ├── chapter1_1_Programming_Model/ │ │ ├── BinarySearch.java │ │ ├── BouncingBall.java │ │ ├── Ex1.java │ │ ├── Ex10.java │ │ ├── Ex11.java │ │ ├── Ex13.java │ │ ├── Ex14.java │ │ ├── Ex15.java │ │ ├── Ex19.java │ │ ├── Ex2.java │ │ ├── Ex20.java │ │ ├── Ex3.java │ │ ├── Ex30.java │ │ ├── Ex31.java │ │ ├── Ex32.java │ │ ├── Ex6.java │ │ ├── Ex7a.java │ │ ├── Ex7b.java │ │ ├── Ex7c.java │ │ ├── Ex8.java │ │ ├── Ex9.java │ │ ├── RightTriangle.java │ │ ├── Sattolo.java │ │ └── StdDrawTest.java │ ├── chapter1_2_Data_Abstraction/ │ │ ├── Accumulator.java │ │ ├── AccumulatorTest.java │ │ ├── Cat.java │ │ ├── Date.java │ │ ├── Flips.java │ │ ├── FlipsMax.java │ │ ├── Interval2DTest.java │ │ ├── Rolls.java │ │ ├── StaticSETofInts.java │ │ ├── VisualAccumulator.java │ │ ├── VisualAccumulatorTest.java │ │ ├── WhiteList.java │ │ ├── in1.txt │ │ └── in2.txt │ ├── chapter1_3_Bags_Queues_Stacks/ │ │ └── ResizingArrayStack.java │ ├── chapter1_4_Analysis_of_Algorithms/ │ │ ├── DoublingRatio.java │ │ ├── DoublingTest.java │ │ ├── Stopwatch.java │ │ ├── StopwatchTest.java │ │ └── ThreeSum.java │ ├── chapter1_5_Case_Study_Union_Find/ │ │ ├── UF.java │ │ └── WeightedQuickUnionUF.java │ ├── chapter2_1_Elementary_Sorts/ │ │ ├── Insertion.java │ │ ├── Selection.java │ │ ├── Shell.java │ │ └── SortCompare.java │ ├── chapter2_2_Mergesort/ │ │ ├── Merge.java │ │ └── MergeBU.java │ ├── chapter2_3_Quicksort/ │ │ ├── Ex25.java │ │ ├── Quick.java │ │ └── Quick3way.java │ ├── chapter2_4_Priority_Queues/ │ │ ├── MaxPQ.java │ │ └── TopM.java │ ├── chapter3_1_Symbol_Tables/ │ │ ├── BinarySearchST.java │ │ ├── FrequencyCounter.java │ │ └── SequentialSearchST.java │ ├── chapter3_2_Binary_Search_Trees/ │ │ └── BST.java │ ├── chapter3_4_Hash_Tables/ │ │ ├── LinearProbingHashST.java │ │ └── SeparateChainingHashST.java │ ├── chapter3_5_Searching_Applications/ │ │ ├── SparseVector.java │ │ └── WhiteFilter.java │ ├── chapter4_1_Undirected_Graphs/ │ │ ├── BreadthFirstPaths.java │ │ ├── CC.java │ │ ├── Cycle.java │ │ ├── DegreesOfSeparation.java │ │ ├── DepthFirstPaths.java │ │ ├── DepthFirstSearch.java │ │ ├── Graph.java │ │ ├── SymbolGraph.java │ │ ├── TestCC.java │ │ ├── TestPaths.java │ │ ├── TestSearch.java │ │ ├── TestSymbolGraph.java │ │ └── TwoColor.java │ ├── chapter4_2_Directed_Graphs/ │ │ ├── DepthFirstOrder.java │ │ ├── Digraph.java │ │ ├── DirectedCycle.java │ │ ├── DirectedDFS.java │ │ ├── KosarajuSCC.java │ │ ├── SymbolDigraph.java │ │ ├── Topological.java │ │ └── TransitiveClosure.java │ ├── chapter4_3_Minimum_Spanning_Tree/ │ │ ├── Edge.java │ │ ├── EdgeWeightedGraph.java │ │ ├── KruskalMST.java │ │ ├── LazyPrimMST.java │ │ ├── PrimMST.java │ │ ├── TestMST.java │ │ └── UF.java │ ├── chapter4_4_Shortest_Paths/ │ │ ├── DijkstraSP.java │ │ ├── DirectedEdge.java │ │ ├── EdgeWeightedDigraph.java │ │ ├── SP.java │ │ └── TestSP.java │ ├── chapter5_3_Substring_Search/ │ │ ├── BoyerMoore.java │ │ ├── KMP.java │ │ └── RabinKarp.java │ ├── chapter6_3_Suffix_Arrays/ │ │ ├── KWIC.java │ │ ├── LRS.java │ │ └── SuffixArray.java │ └── yuki.config.json ├── docs/ │ ├── .nojekyll │ ├── Context/ │ │ ├── 6.1_事件驱动模拟.md │ │ ├── 6.2_B-树.md │ │ ├── 6.3_后缀数组.md │ │ ├── 6.4_网络流算法.md │ │ ├── 6.5_问题规约.md │ │ └── 6.6_不可解性.md │ ├── Fundamentals/ │ │ ├── 1.3_背包、队列和栈.md │ │ ├── 1.4_算法分析.md │ │ └── 1.5_案例研究:union-find算法.md │ ├── Graphs/ │ │ ├── 4.1_无向图.md │ │ ├── 4.2_有向图.md │ │ ├── 4.3_最小生成树.md │ │ └── 4.4_最短路径.md │ ├── README.md │ ├── Searching/ │ │ ├── 3.1_符号表.md │ │ ├── 3.2_二叉查找树.md │ │ ├── 3.3_平衡查找树.md │ │ ├── 3.4_散列表.md │ │ └── 3.5_应用.md │ ├── Sorting/ │ │ ├── 2.1_初级排序算法.md │ │ ├── 2.2_归并排序.md │ │ ├── 2.3_快速排序.md │ │ ├── 2.4_优先队列.md │ │ └── 2.5_应用.md │ ├── Strings/ │ │ ├── 5.2_单词查找树.md │ │ └── 5.3_子字符串查找.md │ ├── _sidebar.md │ └── index.html ├── package.json ├── 每一节可以再看一遍的题.md └── 相关问题解决方法.md
SYMBOL INDEX (1084 symbols across 130 files)
FILE: code/algs4/Alphabet.java
class Alphabet (line 17) | public class Alphabet {
method Alphabet (line 90) | public Alphabet(String alpha) {
method Alphabet (line 117) | private Alphabet(int radix) {
method Alphabet (line 132) | public Alphabet() {
method contains (line 143) | public boolean contains(char c) {
method R (line 153) | @Deprecated
method radix (line 163) | public int radix() {
method lgR (line 172) | public int lgR() {
method toIndex (line 186) | public int toIndex(char c) {
method toIndices (line 201) | public int[] toIndices(String s) {
method toChar (line 216) | public char toChar(int index) {
method toChars (line 231) | public String toChars(int[] indices) {
method main (line 243) | public static void main(String[] args) {
FILE: code/algs4/Bag.java
class Bag (line 54) | public class Bag<Item> implements Iterable<Item> {
class Node (line 59) | private static class Node<Item> {
method Bag (line 67) | public Bag() {
method isEmpty (line 78) | public boolean isEmpty() {
method size (line 87) | public int size() {
method add (line 96) | public void add(Item item) {
method iterator (line 110) | public Iterator<Item> iterator() {
class ListIterator (line 115) | private class ListIterator<Item> implements Iterator<Item> {
method ListIterator (line 118) | public ListIterator(Node<Item> first) {
method hasNext (line 122) | public boolean hasNext() { return current != null; ...
method remove (line 123) | public void remove() { throw new UnsupportedOperationException(...
method next (line 125) | public Item next() {
method main (line 138) | public static void main(String[] args) {
FILE: code/algs4/BinarySearch.java
class BinarySearch (line 42) | public class BinarySearch {
method BinarySearch (line 47) | private BinarySearch() { }
method indexOf (line 56) | public static int indexOf(int[] a, int key) {
method rank (line 79) | @Deprecated
method main (line 91) | public static void main(String[] args) {
FILE: code/algs4/BinaryStdIn.java
class BinaryStdIn (line 38) | public final class BinaryStdIn {
method BinaryStdIn (line 51) | private BinaryStdIn() { }
method fillBuffer (line 53) | private static void fillBuffer() {
method close (line 68) | public static void close() {
method isEmpty (line 81) | public static boolean isEmpty() {
method readBoolean (line 91) | public static boolean readBoolean() {
method readChar (line 107) | public static char readChar() {
method readChar (line 138) | public static char readChar(int r) {
method readString (line 160) | public static String readString() {
method readShort (line 178) | public static short readShort() {
method readInt (line 194) | public static int readInt() {
method readInt (line 212) | public static int readInt(int r) {
method readLong (line 233) | public static long readLong() {
method readDouble (line 250) | public static double readDouble() {
method readFloat (line 260) | public static float readFloat() {
method readByte (line 271) | public static byte readByte() {
method main (line 282) | public static void main(String[] args) {
FILE: code/algs4/BinaryStdOut.java
class BinaryStdOut (line 35) | public final class BinaryStdOut {
method BinaryStdOut (line 42) | private BinaryStdOut() { }
method writeBit (line 47) | private static void writeBit(boolean bit) {
method writeByte (line 60) | private static void writeByte(int x) {
method clearBuffer (line 82) | private static void clearBuffer() {
method flush (line 99) | public static void flush() {
method close (line 113) | public static void close() {
method write (line 128) | public static void write(boolean x) {
method write (line 136) | public static void write(byte x) {
method write (line 144) | public static void write(int x) {
method write (line 158) | public static void write(int x, int r) {
method write (line 179) | public static void write(double x) {
method write (line 187) | public static void write(long x) {
method write (line 202) | public static void write(float x) {
method write (line 210) | public static void write(short x) {
method write (line 220) | public static void write(char x) {
method write (line 232) | public static void write(char x, int r) {
method write (line 251) | public static void write(String s) {
method write (line 264) | public static void write(String s, int r) {
method main (line 274) | public static void main(String[] args) {
FILE: code/algs4/Counter.java
class Counter (line 33) | public class Counter implements Comparable<Counter> {
method Counter (line 43) | public Counter(String id) {
method increment (line 50) | public void increment() {
method tally (line 59) | public int tally() {
method toString (line 68) | public String toString() {
method compareTo (line 83) | @Override
method main (line 97) | public static void main(String[] args) {
FILE: code/algs4/Draw.java
class Draw (line 89) | public final class Draw implements ActionListener, MouseListener, MouseM...
method Draw (line 247) | public Draw(String name) {
method Draw (line 255) | public Draw() {
method init (line 259) | private void init() {
method setLocationOnScreen (line 308) | public void setLocationOnScreen(int x, int y) {
method setDefaultCloseOperation (line 320) | public void setDefaultCloseOperation(int value) {
method setCanvasSize (line 336) | public void setCanvasSize(int canvasWidth, int canvasHeight) {
method createMenuBar (line 347) | private JMenuBar createMenuBar() {
method setXscale (line 367) | public void setXscale() {
method setYscale (line 374) | public void setYscale() {
method setXscale (line 384) | public void setXscale(double min, double max) {
method setYscale (line 396) | public void setYscale(double min, double max) {
method scaleX (line 403) | private double scaleX(double x) { return width * (x - xmin) / (xmax ...
method scaleY (line 404) | private double scaleY(double y) { return height * (ymax - y) / (ymax ...
method factorX (line 405) | private double factorX(double w) { return w * width / Math.abs(xmax -...
method factorY (line 406) | private double factorY(double h) { return h * height / Math.abs(ymax -...
method userX (line 407) | private double userX(double x) { return xmin + x * (xmax - xmin) / w...
method userY (line 408) | private double userY(double y) { return ymax - y * (ymax - ymin) / h...
method clear (line 414) | public void clear() {
method clear (line 423) | public void clear(Color color) {
method getPenRadius (line 435) | public double getPenRadius() {
method setPenRadius (line 442) | public void setPenRadius() {
method setPenRadius (line 452) | public void setPenRadius(double r) {
method getPenColor (line 465) | public Color getPenColor() {
method setPenColor (line 472) | public void setPenColor() {
method setPenColor (line 481) | public void setPenColor(Color color) {
method setPenColor (line 494) | public void setPenColor(int red, int green, int blue) {
method xorOn (line 505) | public void xorOn() {
method xorOff (line 512) | public void xorOff() {
method getJLabel (line 521) | public JLabel getJLabel() {
method getFont (line 530) | public Font getFont() {
method setFont (line 537) | public void setFont() {
method setFont (line 546) | public void setFont(Font font) {
method line (line 563) | public void line(double x0, double y0, double x1, double y1) {
method pixel (line 574) | private void pixel(double x, double y) {
method point (line 584) | public void point(double x, double y) {
method circle (line 604) | public void circle(double x, double y, double r) {
method filledCircle (line 623) | public void filledCircle(double x, double y, double r) {
method ellipse (line 644) | public void ellipse(double x, double y, double semiMajorAxis, double s...
method filledEllipse (line 664) | public void filledEllipse(double x, double y, double semiMajorAxis, do...
method arc (line 687) | public void arc(double x, double y, double r, double angle1, double an...
method square (line 707) | public void square(double x, double y, double r) {
method filledSquare (line 726) | public void filledSquare(double x, double y, double r) {
method rectangle (line 747) | public void rectangle(double x, double y, double halfWidth, double hal...
method filledRectangle (line 768) | public void filledRectangle(double x, double y, double halfWidth, doub...
method polygon (line 786) | public void polygon(double[] x, double[] y) {
method filledPolygon (line 803) | public void filledPolygon(double[] x, double[] y) {
method getImage (line 820) | private static BufferedImage getImage(String filename) {
method picture (line 860) | public void picture(double x, double y, String filename) {
method picture (line 884) | public void picture(double x, double y, String filename, double degree...
method picture (line 911) | public void picture(double x, double y, String filename, double w, dou...
method picture (line 943) | public void picture(double x, double y, String filename, double w, dou...
method text (line 975) | public void text(double x, double y, String s) {
method text (line 995) | public void text(double x, double y, String s, double degrees) {
method textLeft (line 1010) | public void textLeft(double x, double y, String s) {
method show (line 1035) | public void show(int t) {
method show (line 1053) | public void show() {
method draw (line 1059) | private void draw() {
method save (line 1070) | public void save(String filename) {
method actionPerformed (line 1113) | @Override
method addListener (line 1134) | public void addListener(DrawListener listener) {
method mousePressed (line 1157) | public boolean mousePressed() {
method mouseX (line 1167) | public double mouseX() {
method mouseY (line 1178) | public double mouseY() {
method mouseClicked (line 1189) | @Override
method mouseEntered (line 1197) | @Override
method mouseExited (line 1205) | @Override
method mousePressed (line 1213) | @Override
method mouseReleased (line 1230) | @Override
method mouseDragged (line 1244) | @Override
method mouseMoved (line 1258) | @Override
method hasNextKeyTyped (line 1276) | public boolean hasNextKeyTyped() {
method nextKeyTyped (line 1287) | public char nextKeyTyped() {
method isKeyPressed (line 1305) | public boolean isKeyPressed(int keycode) {
method keyTyped (line 1314) | @Override
method keyPressed (line 1328) | @Override
method keyReleased (line 1342) | @Override
method main (line 1361) | public static void main(String[] args) {
FILE: code/algs4/DrawListener.java
type DrawListener (line 11) | public interface DrawListener {
method mousePressed (line 19) | void mousePressed(double x, double y);
method mouseDragged (line 27) | void mouseDragged(double x, double y);
method mouseReleased (line 35) | void mouseReleased(double x, double y);
method keyTyped (line 42) | void keyTyped(char c);
method keyPressed (line 49) | void keyPressed(int keycode);
method keyReleased (line 56) | void keyReleased(int keycode);
FILE: code/algs4/Heap.java
class Heap (line 36) | public class Heap {
method Heap (line 39) | private Heap() { }
method sort (line 45) | public static void sort(Comparable[] pq) {
method sink (line 59) | private static void sink(Comparable[] pq, int k, int n) {
method less (line 73) | private static boolean less(Comparable[] pq, int i, int j) {
method exch (line 77) | private static void exch(Object[] pq, int i, int j) {
method less (line 84) | private static boolean less(Comparable v, Comparable w) {
method isSorted (line 92) | private static boolean isSorted(Comparable[] a) {
method show (line 100) | private static void show(Comparable[] a) {
method main (line 112) | public static void main(String[] args) {
FILE: code/algs4/HexDump.java
class HexDump (line 45) | public class HexDump {
method HexDump (line 48) | private HexDump() { }
method main (line 59) | public static void main(String[] args) {
FILE: code/algs4/In.java
class In (line 56) | public final class In {
method In (line 87) | public In() {
method In (line 99) | public In(Socket socket) {
method In (line 118) | public In(URL url) {
method In (line 138) | public In(File file) {
method In (line 161) | public In(String name) {
method In (line 208) | public In(Scanner scanner) {
method exists (line 218) | public boolean exists() {
method isEmpty (line 233) | public boolean isEmpty() {
method hasNextLine (line 246) | public boolean hasNextLine() {
method hasNextChar (line 258) | public boolean hasNextChar() {
method readLine (line 271) | public String readLine() {
method readChar (line 287) | public char readChar() {
method readAll (line 302) | public String readAll() {
method readString (line 318) | public String readString() {
method readInt (line 328) | public int readInt() {
method readDouble (line 338) | public double readDouble() {
method readFloat (line 348) | public float readFloat() {
method readLong (line 358) | public long readLong() {
method readShort (line 368) | public short readShort() {
method readByte (line 380) | public byte readByte() {
method readBoolean (line 391) | public boolean readBoolean() {
method readAllStrings (line 406) | public String[] readAllStrings() {
method readAllLines (line 424) | public String[] readAllLines() {
method readAllInts (line 439) | public int[] readAllInts() {
method readAllLongs (line 453) | public long[] readAllLongs() {
method readAllDoubles (line 467) | public double[] readAllDoubles() {
method close (line 480) | public void close() {
method readInts (line 492) | @Deprecated
method readDoubles (line 505) | @Deprecated
method readStrings (line 518) | @Deprecated
method readInts (line 530) | @Deprecated
method readDoubles (line 542) | @Deprecated
method readStrings (line 554) | @Deprecated
method main (line 564) | public static void main(String[] args) {
FILE: code/algs4/IndexMinPQ.java
class IndexMinPQ (line 44) | public class IndexMinPQ<Key extends Comparable<Key>> implements Iterable...
method IndexMinPQ (line 58) | public IndexMinPQ(int maxN) {
method isEmpty (line 75) | public boolean isEmpty() {
method contains (line 87) | public boolean contains(int i) {
method size (line 97) | public int size() {
method insert (line 110) | public void insert(int i, Key key) {
method minIndex (line 126) | public int minIndex() {
method minKey (line 137) | public Key minKey() {
method delMin (line 147) | public int delMin() {
method keyOf (line 167) | public Key keyOf(int i) {
method changeKey (line 181) | public void changeKey(int i, Key key) {
method change (line 197) | @Deprecated
method decreaseKey (line 211) | public void decreaseKey(int i, Key key) {
method increaseKey (line 229) | public void increaseKey(int i, Key key) {
method delete (line 245) | public void delete(int i) {
method greater (line 260) | private boolean greater(int i, int j) {
method exch (line 264) | private void exch(int i, int j) {
method swim (line 276) | private void swim(int k) {
method sink (line 283) | private void sink(int k) {
method iterator (line 305) | public Iterator<Integer> iterator() { return new HeapIterator(); }
class HeapIterator (line 307) | private class HeapIterator implements Iterator<Integer> {
method HeapIterator (line 313) | public HeapIterator() {
method hasNext (line 319) | public boolean hasNext() { return !copy.isEmpty(); ...
method remove (line 320) | public void remove() { throw new UnsupportedOperationException(...
method next (line 322) | public Integer next() {
method main (line 334) | public static void main(String[] args) {
FILE: code/algs4/Interval1D.java
class Interval1D (line 29) | public class Interval1D {
method Interval1D (line 60) | public Interval1D(double min, double max) {
method left (line 83) | @Deprecated
method right (line 93) | @Deprecated
method min (line 103) | public double min() {
method max (line 112) | public double max() {
method intersects (line 123) | public boolean intersects(Interval1D that) {
method contains (line 136) | public boolean contains(double x) {
method length (line 145) | public double length() {
method toString (line 154) | public String toString() {
method equals (line 165) | public boolean equals(Object other) {
method hashCode (line 178) | public int hashCode() {
class MinEndpointComparator (line 185) | private static class MinEndpointComparator implements Comparator<Inter...
method compare (line 186) | public int compare(Interval1D a, Interval1D b) {
class MaxEndpointComparator (line 196) | private static class MaxEndpointComparator implements Comparator<Inter...
method compare (line 197) | public int compare(Interval1D a, Interval1D b) {
class LengthComparator (line 207) | private static class LengthComparator implements Comparator<Interval1D> {
method compare (line 208) | public int compare(Interval1D a, Interval1D b) {
method main (line 225) | public static void main(String[] args) {
FILE: code/algs4/Interval2D.java
class Interval2D (line 29) | public class Interval2D {
method Interval2D (line 38) | public Interval2D(Interval1D x, Interval1D y) {
method intersects (line 49) | public boolean intersects(Interval2D that) {
method contains (line 60) | public boolean contains(Point2D p) {
method area (line 68) | public double area() {
method toString (line 77) | public String toString() {
method equals (line 86) | public boolean equals(Object other) {
method hashCode (line 99) | public int hashCode() {
method draw (line 108) | public void draw() {
method main (line 119) | public static void main(String[] args) {
FILE: code/algs4/MinPQ.java
class MinPQ (line 48) | public class MinPQ<Key> implements Iterable<Key> {
method MinPQ (line 58) | public MinPQ(int initCapacity) {
method MinPQ (line 66) | public MinPQ() {
method MinPQ (line 77) | public MinPQ(int initCapacity, Comparator<Key> comparator) {
method MinPQ (line 88) | public MinPQ(Comparator<Key> comparator) {
method MinPQ (line 99) | public MinPQ(Key[] keys) {
method isEmpty (line 115) | public boolean isEmpty() {
method size (line 124) | public int size() {
method min (line 134) | public Key min() {
method resize (line 140) | private void resize(int capacity) {
method insert (line 154) | public void insert(Key x) {
method delMin (line 170) | public Key delMin() {
method swim (line 186) | private void swim(int k) {
method sink (line 193) | private void sink(int k) {
method greater (line 206) | private boolean greater(int i, int j) {
method exch (line 215) | private void exch(int i, int j) {
method isMinHeap (line 222) | private boolean isMinHeap() {
method isMinHeap (line 227) | private boolean isMinHeap(int k) {
method iterator (line 245) | public Iterator<Key> iterator() { return new HeapIterator(); }
class HeapIterator (line 247) | private class HeapIterator implements Iterator<Key> {
method HeapIterator (line 253) | public HeapIterator() {
method hasNext (line 260) | public boolean hasNext() { return !copy.isEmpty(); ...
method remove (line 261) | public void remove() { throw new UnsupportedOperationException(...
method next (line 263) | public Key next() {
method main (line 274) | public static void main(String[] args) {
FILE: code/algs4/Out.java
class Out (line 33) | public class Out {
method Out (line 48) | public Out(OutputStream os) {
method Out (line 61) | public Out() {
method Out (line 70) | public Out(Socket socket) {
method Out (line 86) | public Out(String filename) {
method close (line 100) | public void close() {
method println (line 107) | public void println() {
method println (line 116) | public void println(Object x) {
method println (line 125) | public void println(boolean x) {
method println (line 134) | public void println(char x) {
method println (line 143) | public void println(double x) {
method println (line 152) | public void println(float x) {
method println (line 161) | public void println(int x) {
method println (line 170) | public void println(long x) {
method println (line 181) | public void println(byte x) {
method print (line 190) | public void print() {
method print (line 199) | public void print(Object x) {
method print (line 209) | public void print(boolean x) {
method print (line 219) | public void print(char x) {
method print (line 229) | public void print(double x) {
method print (line 239) | public void print(float x) {
method print (line 249) | public void print(int x) {
method print (line 259) | public void print(long x) {
method print (line 269) | public void print(byte x) {
method printf (line 281) | public void printf(String format, Object... args) {
method printf (line 294) | public void printf(Locale locale, String format, Object... args) {
method main (line 305) | public static void main(String[] args) {
FILE: code/algs4/Particle.java
class Particle (line 29) | public class Particle {
method Particle (line 51) | public Particle(double rx, double ry, double vx, double vy, double rad...
method Particle (line 66) | public Particle() {
method move (line 82) | public void move(double dt) {
method draw (line 90) | public void draw() {
method count (line 105) | public int count() {
method timeToHit (line 118) | public double timeToHit(Particle that) {
method timeToHitVerticalWall (line 144) | public double timeToHitVerticalWall() {
method timeToHitHorizontalWall (line 159) | public double timeToHitHorizontalWall() {
method bounceOff (line 172) | public void bounceOff(Particle that) {
method bounceOffVerticalWall (line 203) | public void bounceOffVerticalWall() {
method bounceOffHorizontalWall (line 213) | public void bounceOffHorizontalWall() {
method kineticEnergy (line 225) | public double kineticEnergy() {
FILE: code/algs4/Picture.java
class Picture (line 63) | public final class Picture implements ActionListener {
method Picture (line 79) | public Picture(int width, int height) {
method Picture (line 94) | public Picture(Picture picture) {
method Picture (line 110) | public Picture(String filename) {
method Picture (line 146) | public Picture(File file) {
method getJLabel (line 167) | public JLabel getJLabel() {
method setOriginUpperLeft (line 176) | public void setOriginUpperLeft() {
method setOriginLowerLeft (line 183) | public void setOriginLowerLeft() {
method show (line 190) | public void show() {
method height (line 226) | public int height() {
method width (line 235) | public int width() {
method validateRow (line 239) | private void validateRow(int row) {
method validateCol (line 244) | private void validateCol(int col) {
method get (line 257) | public Color get(int col, int row) {
method set (line 273) | public void set(int col, int row, Color color) {
method equals (line 288) | public boolean equals(Object other) {
method hashCode (line 307) | public int hashCode() {
method save (line 317) | public void save(String name) {
method save (line 326) | public void save(File file) {
method actionPerformed (line 346) | @Override
method main (line 364) | public static void main(String[] args) {
FILE: code/algs4/PictureDump.java
class PictureDump (line 35) | public class PictureDump {
method PictureDump (line 38) | private PictureDump() { }
method main (line 48) | public static void main(String[] args) {
FILE: code/algs4/Point2D.java
class Point2D (line 31) | public final class Point2D implements Comparable<Point2D> {
method Point2D (line 59) | public Point2D(double x, double y) {
method x (line 75) | public double x() {
method y (line 83) | public double y() {
method r (line 91) | public double r() {
method theta (line 99) | public double theta() {
method angleTo (line 107) | private double angleTo(Point2D that) {
method ccw (line 120) | public static int ccw(Point2D a, Point2D b, Point2D c) {
method area2 (line 134) | public static double area2(Point2D a, Point2D b, Point2D c) {
method distanceTo (line 143) | public double distanceTo(Point2D that) {
method distanceSquaredTo (line 154) | public double distanceSquaredTo(Point2D that) {
method compareTo (line 172) | public int compareTo(Point2D that) {
method polarOrder (line 185) | public Comparator<Point2D> polarOrder() {
method atan2Order (line 194) | public Comparator<Point2D> atan2Order() {
method distanceToOrder (line 203) | public Comparator<Point2D> distanceToOrder() {
class XOrder (line 208) | private static class XOrder implements Comparator<Point2D> {
method compare (line 209) | public int compare(Point2D p, Point2D q) {
class YOrder (line 217) | private static class YOrder implements Comparator<Point2D> {
method compare (line 218) | public int compare(Point2D p, Point2D q) {
class ROrder (line 226) | private static class ROrder implements Comparator<Point2D> {
method compare (line 227) | public int compare(Point2D p, Point2D q) {
class Atan2Order (line 236) | private class Atan2Order implements Comparator<Point2D> {
method compare (line 237) | public int compare(Point2D q1, Point2D q2) {
class PolarOrder (line 247) | private class PolarOrder implements Comparator<Point2D> {
method compare (line 248) | public int compare(Point2D q1, Point2D q2) {
class DistanceToOrder (line 268) | private class DistanceToOrder implements Comparator<Point2D> {
method compare (line 269) | public int compare(Point2D p, Point2D q) {
method equals (line 286) | @Override
method toString (line 299) | @Override
method hashCode (line 308) | @Override
method draw (line 318) | public void draw() {
method drawTo (line 326) | public void drawTo(Point2D that) {
method main (line 336) | public static void main(String[] args) {
FILE: code/algs4/Queue.java
class Queue (line 41) | public class Queue<Item> implements Iterable<Item> {
class Node (line 47) | private static class Node<Item> {
method Queue (line 55) | public Queue() {
method isEmpty (line 66) | public boolean isEmpty() {
method size (line 75) | public int size() {
method peek (line 85) | public Item peek() {
method enqueue (line 95) | public void enqueue(Item item) {
method dequeue (line 111) | public Item dequeue() {
method toString (line 125) | public String toString() {
method iterator (line 139) | public Iterator<Item> iterator() {
class ListIterator (line 144) | private class ListIterator<Item> implements Iterator<Item> {
method ListIterator (line 147) | public ListIterator(Node<Item> first) {
method hasNext (line 151) | public boolean hasNext() { return current != null; ...
method remove (line 152) | public void remove() { throw new UnsupportedOperationException(...
method next (line 154) | public Item next() {
method main (line 168) | public static void main(String[] args) {
FILE: code/algs4/SET.java
class SET (line 53) | public class SET<Key extends Comparable<Key>> implements Iterable<Key> {
method SET (line 59) | public SET() {
method SET (line 68) | public SET(SET<Key> x) {
method add (line 78) | public void add(Key key) {
method contains (line 92) | public boolean contains(Key key) {
method delete (line 103) | public void delete(Key key) {
method size (line 113) | public int size() {
method isEmpty (line 123) | public boolean isEmpty() {
method iterator (line 134) | public Iterator<Key> iterator() {
method max (line 144) | public Key max() {
method min (line 155) | public Key min() {
method ceiling (line 169) | public Key ceiling(Key key) {
method floor (line 184) | public Key floor(Key key) {
method union (line 198) | public SET<Key> union(SET<Key> that) {
method intersects (line 217) | public SET<Key> intersects(SET<Key> that) {
method equals (line 245) | @Override
method hashCode (line 260) | @Override
method toString (line 271) | @Override
method main (line 282) | public static void main(String[] args) {
FILE: code/algs4/ST.java
class ST (line 53) | public class ST<Key extends Comparable<Key>, Value> implements Iterable<...
method ST (line 60) | public ST() {
method get (line 73) | public Value get(Key key) {
method put (line 88) | public void put(Key key, Value val) {
method delete (line 101) | public void delete(Key key) {
method contains (line 114) | public boolean contains(Key key) {
method size (line 124) | public int size() {
method isEmpty (line 133) | public boolean isEmpty() {
method keys (line 145) | public Iterable<Key> keys() {
method iterator (line 160) | @Deprecated
method min (line 171) | public Key min() {
method max (line 182) | public Key max() {
method ceiling (line 195) | public Key ceiling(Key key) {
method floor (line 210) | public Key floor(Key key) {
method main (line 222) | public static void main(String[] args) {
FILE: code/algs4/Stack.java
class Stack (line 49) | public class Stack<Item> implements Iterable<Item> {
class Node (line 54) | private static class Node<Item> {
method Stack (line 62) | public Stack() {
method isEmpty (line 72) | public boolean isEmpty() {
method size (line 81) | public int size() {
method push (line 90) | public void push(Item item) {
method pop (line 104) | public Item pop() {
method peek (line 119) | public Item peek() {
method toString (line 129) | public String toString() {
method iterator (line 144) | public Iterator<Item> iterator() {
class ListIterator (line 149) | private class ListIterator<Item> implements Iterator<Item> {
method ListIterator (line 152) | public ListIterator(Node<Item> first) {
method hasNext (line 156) | public boolean hasNext() {
method remove (line 160) | public void remove() {
method next (line 164) | public Item next() {
method main (line 178) | public static void main(String[] args) {
FILE: code/algs4/StdDraw.java
class StdDraw (line 470) | public final class StdDraw implements ActionListener, MouseListener, Mou...
method StdDraw (line 621) | private StdDraw() { }
method setCanvasSize (line 636) | public static void setCanvasSize() {
method setCanvasSize (line 652) | public static void setCanvasSize(int canvasWidth, int canvasHeight) {
method init (line 661) | private static void init() {
method createMenuBar (line 703) | private static JMenuBar createMenuBar() {
method setXscale (line 723) | public static void setXscale() {
method setYscale (line 730) | public static void setYscale() {
method setScale (line 738) | public static void setScale() {
method setXscale (line 750) | public static void setXscale(double min, double max) {
method setYscale (line 766) | public static void setYscale(double min, double max) {
method setScale (line 782) | public static void setScale(double min, double max) {
method scaleX (line 794) | private static double scaleX(double x) { return width * (x - xmin) /...
method scaleY (line 795) | private static double scaleY(double y) { return height * (ymax - y) /...
method factorX (line 796) | private static double factorX(double w) { return w * width / Math.abs...
method factorY (line 797) | private static double factorY(double h) { return h * height / Math.abs...
method userX (line 798) | private static double userX(double x) { return xmin + x * (xmax - xm...
method userY (line 799) | private static double userY(double y) { return ymax - y * (ymax - ym...
method clear (line 805) | public static void clear() {
method clear (line 814) | public static void clear(Color color) {
method getPenRadius (line 826) | public static double getPenRadius() {
method setPenRadius (line 836) | public static void setPenRadius() {
method setPenRadius (line 849) | public static void setPenRadius(double radius) {
method getPenColor (line 863) | public static Color getPenColor() {
method setPenColor (line 870) | public static void setPenColor() {
method setPenColor (line 886) | public static void setPenColor(Color color) {
method setPenColor (line 901) | public static void setPenColor(int red, int green, int blue) {
method getFont (line 913) | public static Font getFont() {
method setFont (line 920) | public static void setFont() {
method setFont (line 929) | public static void setFont(Font font) {
method line (line 948) | public static void line(double x0, double y0, double x1, double y1) {
method pixel (line 961) | private static void pixel(double x, double y) {
method point (line 973) | public static void point(double x, double y) {
method circle (line 996) | public static void circle(double x, double y, double radius) {
method filledCircle (line 1015) | public static void filledCircle(double x, double y, double radius) {
method ellipse (line 1038) | public static void ellipse(double x, double y, double semiMajorAxis, d...
method filledEllipse (line 1061) | public static void filledEllipse(double x, double y, double semiMajorA...
method arc (line 1086) | public static void arc(double x, double y, double radius, double angle...
method square (line 1106) | public static void square(double x, double y, double halfLength) {
method filledSquare (line 1125) | public static void filledSquare(double x, double y, double halfLength) {
method rectangle (line 1146) | public static void rectangle(double x, double y, double halfWidth, dou...
method filledRectangle (line 1167) | public static void filledRectangle(double x, double y, double halfWidt...
method polygon (line 1191) | public static void polygon(double[] x, double[] y) {
method filledPolygon (line 1218) | public static void filledPolygon(double[] x, double[] y) {
method getImage (line 1239) | private static Image getImage(String filename) {
method picture (line 1329) | public static void picture(double x, double y, String filename) {
method picture (line 1355) | public static void picture(double x, double y, String filename, double...
method picture (line 1387) | public static void picture(double x, double y, String filename, double...
method picture (line 1422) | public static void picture(double x, double y, String filename, double...
method text (line 1454) | public static void text(double x, double y, String text) {
method text (line 1474) | public static void text(double x, double y, String text, double degree...
method textLeft (line 1490) | public static void textLeft(double x, double y, String text) {
method textRight (line 1508) | public static void textRight(double x, double y, String text) {
method show (line 1528) | @Deprecated
method pause (line 1553) | public static void pause(int t) {
method show (line 1574) | public static void show() {
method draw (line 1580) | private static void draw() {
method enableDoubleBuffering (line 1590) | public static void enableDoubleBuffering() {
method disableDoubleBuffering (line 1600) | public static void disableDoubleBuffering() {
method save (line 1616) | public static void save(String filename) {
method actionPerformed (line 1660) | @Override
method mousePressed (line 1680) | public static boolean mousePressed() {
method mouseX (line 1691) | public static double mouseX() {
method mouseY (line 1702) | public static double mouseY() {
method mouseClicked (line 1712) | @Override
method mouseEntered (line 1718) | @Override
method mouseExited (line 1724) | @Override
method mousePressed (line 1730) | @Override
method mouseReleased (line 1742) | @Override
method mouseDragged (line 1752) | @Override
method mouseMoved (line 1763) | @Override
method hasNextKeyTyped (line 1782) | public static boolean hasNextKeyTyped() {
method nextKeyTyped (line 1800) | public static char nextKeyTyped() {
method isKeyPressed (line 1821) | public static boolean isKeyPressed(int keycode) {
method keyTyped (line 1831) | @Override
method keyPressed (line 1841) | @Override
method keyReleased (line 1851) | @Override
method main (line 1866) | public static void main(String[] args) {
FILE: code/algs4/StdIn.java
class StdIn (line 192) | public final class StdIn {
method StdIn (line 217) | private StdIn() { }
method isEmpty (line 230) | public static boolean isEmpty() {
method hasNextLine (line 243) | public static boolean hasNextLine() {
method hasNextChar (line 255) | public static boolean hasNextChar() {
method readLine (line 269) | public static String readLine() {
method readChar (line 286) | public static char readChar() {
method readAll (line 302) | public static String readAll() {
method readString (line 319) | public static String readString() {
method readInt (line 330) | public static int readInt() {
method readDouble (line 341) | public static double readDouble() {
method readFloat (line 352) | public static float readFloat() {
method readLong (line 363) | public static long readLong() {
method readShort (line 374) | public static short readShort() {
method readByte (line 385) | public static byte readByte() {
method readBoolean (line 399) | public static boolean readBoolean() {
method readAllStrings (line 413) | public static String[] readAllStrings() {
method readAllLines (line 431) | public static String[] readAllLines() {
method readAllInts (line 445) | public static int[] readAllInts() {
method readAllLongs (line 459) | public static long[] readAllLongs() {
method readAllDoubles (line 473) | public static double[] readAllDoubles() {
method resync (line 492) | private static void resync() {
method setScanner (line 496) | private static void setScanner(Scanner scanner) {
method readInts (line 508) | @Deprecated
method readDoubles (line 520) | @Deprecated
method readStrings (line 530) | @Deprecated
method main (line 541) | public static void main(String[] args) {
FILE: code/algs4/StdOut.java
class StdOut (line 62) | public final class StdOut {
method StdOut (line 84) | private StdOut() { }
method close (line 89) | public static void close() {
method println (line 96) | public static void println() {
method println (line 105) | public static void println(Object x) {
method println (line 114) | public static void println(boolean x) {
method println (line 123) | public static void println(char x) {
method println (line 132) | public static void println(double x) {
method println (line 141) | public static void println(float x) {
method println (line 150) | public static void println(int x) {
method println (line 159) | public static void println(long x) {
method println (line 168) | public static void println(short x) {
method println (line 179) | public static void println(byte x) {
method print (line 186) | public static void print() {
method print (line 195) | public static void print(Object x) {
method print (line 205) | public static void print(boolean x) {
method print (line 215) | public static void print(char x) {
method print (line 225) | public static void print(double x) {
method print (line 235) | public static void print(float x) {
method print (line 245) | public static void print(int x) {
method print (line 255) | public static void print(long x) {
method print (line 265) | public static void print(short x) {
method print (line 275) | public static void print(byte x) {
method printf (line 288) | public static void printf(String format, Object... args) {
method printf (line 301) | public static void printf(Locale locale, String format, Object... args) {
method main (line 311) | public static void main(String[] args) {
FILE: code/algs4/StdRandom.java
class StdRandom (line 67) | public final class StdRandom {
method StdRandom (line 80) | private StdRandom() { }
method setSeed (line 90) | public static void setSeed(long s) {
method getSeed (line 100) | public static long getSeed() {
method uniform (line 109) | public static double uniform() {
method uniform (line 120) | public static int uniform(int n) {
method random (line 136) | @Deprecated
method uniform (line 150) | public static int uniform(int a, int b) {
method uniform (line 164) | public static double uniform(double a, double b) {
method bernoulli (line 178) | public static boolean bernoulli(double p) {
method bernoulli (line 191) | public static boolean bernoulli() {
method gaussian (line 201) | public static double gaussian() {
method gaussian (line 224) | public static double gaussian(double mu, double sigma) {
method geometric (line 238) | public static int geometric(double p) {
method poisson (line 252) | public static int poisson(double lambda) {
method pareto (line 274) | public static double pareto() {
method pareto (line 287) | public static double pareto(double alpha) {
method cauchy (line 298) | public static double cauchy() {
method discrete (line 312) | public static int discrete(double[] probabilities) {
method discrete (line 347) | public static int discrete(int[] frequencies) {
method exp (line 382) | public static double exp(double lambda) {
method shuffle (line 394) | public static void shuffle(Object[] a) {
method shuffle (line 411) | public static void shuffle(double[] a) {
method shuffle (line 428) | public static void shuffle(int[] a) {
method shuffle (line 450) | public static void shuffle(Object[] a, int lo, int hi) {
method shuffle (line 472) | public static void shuffle(double[] a, int lo, int hi) {
method shuffle (line 494) | public static void shuffle(int[] a, int lo, int hi) {
method main (line 512) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/BinarySearch.java
class BinarySearch (line 10) | public class BinarySearch {
method rank (line 12) | public static int rank(int key, int[] a) {
method main (line 28) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/BouncingBall.java
class BouncingBall (line 5) | public class BouncingBall {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex1.java
class Ex1 (line 5) | public class Ex1 {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex10.java
class Ex10 (line 5) | public class Ex10 {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex11.java
class Ex11 (line 6) | public class Ex11 {
method main (line 8) | public static void main(String[] args) {
method printBoolArr (line 25) | public static void printBoolArr (boolean[][] arr) {
FILE: code/chapter1_1_Programming_Model/Ex13.java
class Ex13 (line 6) | public class Ex13 {
method main (line 8) | public static void main(String[] args) {
method arrReverse (line 22) | public static int[][] arrReverse(int[][] arr) {
method printArr (line 31) | public static void printArr(int[][] arr) {
FILE: code/chapter1_1_Programming_Model/Ex14.java
class Ex14 (line 5) | public class Ex14 {
method main (line 7) | public static void main(String[] args) {
method lg (line 13) | public static int lg(int N) {
method n2 (line 21) | public static int n2(int n) {
FILE: code/chapter1_1_Programming_Model/Ex15.java
class Ex15 (line 5) | public class Ex15 {
method main (line 7) | public static void main(String[] args) {
method histogram (line 16) | public static int[] histogram(int[] a, int M) {
FILE: code/chapter1_1_Programming_Model/Ex19.java
class Ex19 (line 5) | public class Ex19 {
method F (line 10) | public static long F(int N) {
method main (line 20) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex2.java
class Ex2 (line 5) | public class Ex2 {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex20.java
class Ex20 (line 5) | public class Ex20 {
method main (line 7) | public static void main(String[] args) {
method ln10 (line 13) | public static double ln10(int N) {
FILE: code/chapter1_1_Programming_Model/Ex3.java
class Ex3 (line 6) | public class Ex3 {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex30.java
class Ex30 (line 5) | public class Ex30 {
method main (line 7) | public static void main(String[] args) {
method setArrBoolean (line 21) | public static void setArrBoolean(boolean[][] arr) {
FILE: code/chapter1_1_Programming_Model/Ex31.java
class Ex31 (line 8) | public class Ex31 {
class Point (line 10) | static class Point {
method Point (line 13) | public Point(double x, double y) {
method main (line 20) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex32.java
class Ex32 (line 8) | public class Ex32 {
method main (line 10) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex6.java
class Ex6 (line 5) | public class Ex6 {
method main (line 6) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex7a.java
class Ex7a (line 5) | public class Ex7a {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex7b.java
class Ex7b (line 5) | public class Ex7b {
method main (line 6) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex7c.java
class Ex7c (line 5) | public class Ex7c {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex8.java
class Ex8 (line 3) | public class Ex8 {
method main (line 5) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Ex9.java
class Ex9 (line 5) | public class Ex9 {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/RightTriangle.java
class RightTriangle (line 5) | public class RightTriangle {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/Sattolo.java
class Sattolo (line 6) | public class Sattolo {
method Sattolo (line 8) | private Sattolo() { }
method cycle (line 10) | public static void cycle(Object[] a) {
method main (line 20) | public static void main(String[] args) {
FILE: code/chapter1_1_Programming_Model/StdDrawTest.java
class StdDrawTest (line 6) | public class StdDrawTest {
method main (line 7) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/Accumulator.java
class Accumulator (line 3) | public class Accumulator {
method addDataValue (line 6) | public void addDataValue(double val) {
method mean (line 10) | public double mean() {
method toString (line 13) | public String toString() {
FILE: code/chapter1_2_Data_Abstraction/AccumulatorTest.java
class AccumulatorTest (line 6) | public class AccumulatorTest {
method main (line 8) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/Cat.java
class Cat (line 6) | public class Cat {
method main (line 8) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/Date.java
class Date (line 3) | public class Date {
method Date (line 8) | public Date(int m, int d, int y) {
method month (line 13) | public int month() {
method day (line 16) | public int day() {
method year (line 19) | public int year() {
method toString (line 22) | public String toString() {
method equals (line 25) | public boolean equals(Object x) {
FILE: code/chapter1_2_Data_Abstraction/Flips.java
class Flips (line 7) | public class Flips {
method main (line 9) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/FlipsMax.java
class FlipsMax (line 7) | public class FlipsMax {
method max (line 9) | public static Counter max(Counter x, Counter y) {
method main (line 16) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/Interval2DTest.java
class Interval2DTest (line 9) | public class Interval2DTest {
method main (line 11) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/Rolls.java
class Rolls (line 7) | public class Rolls {
method main (line 9) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/StaticSETofInts.java
class StaticSETofInts (line 5) | public class StaticSETofInts {
method StaticSETofInts (line 7) | public StaticSETofInts(int[] keys) {
method contains (line 14) | public boolean contains(int key) {
method rank (line 17) | private int rank(int key) {
FILE: code/chapter1_2_Data_Abstraction/VisualAccumulator.java
class VisualAccumulator (line 5) | public class VisualAccumulator {
method VisualAccumulator (line 9) | public VisualAccumulator(int trials, double max) {
method addDataValue (line 15) | public void addDataValue(double val) {
method mean (line 23) | public double mean() {
method toString (line 26) | public String toString() {
FILE: code/chapter1_2_Data_Abstraction/VisualAccumulatorTest.java
class VisualAccumulatorTest (line 6) | public class VisualAccumulatorTest {
method main (line 8) | public static void main(String[] args) {
FILE: code/chapter1_2_Data_Abstraction/WhiteList.java
class WhiteList (line 7) | public class WhiteList {
method main (line 8) | public static void main(String[] args) {
FILE: code/chapter1_3_Bags_Queues_Stacks/ResizingArrayStack.java
class ResizingArrayStack (line 5) | public class ResizingArrayStack<Item> implements Iterable<Item>{
method isEmpty (line 8) | public boolean isEmpty() {
method size (line 11) | public int size() {
method resize (line 14) | public void resize(int max) {
method push (line 21) | public void push(Item item) {
method pop (line 26) | public Item pop() {
method iterator (line 34) | @Override
class ReverseArrayIterator (line 38) | private class ReverseArrayIterator implements Iterator<Item> {
method hasNext (line 40) | public boolean hasNext() {
method next (line 43) | public Item next() {
method remove (line 46) | public void remove() {}
FILE: code/chapter1_4_Analysis_of_Algorithms/DoublingRatio.java
class DoublingRatio (line 6) | public class DoublingRatio {
method timeTrial (line 8) | public static double timeTrial(int N) {
method main (line 19) | public static void main(String[] args) {
FILE: code/chapter1_4_Analysis_of_Algorithms/DoublingTest.java
class DoublingTest (line 6) | public class DoublingTest {
method timeTrial (line 8) | public static double timeTrial(int N) {
method main (line 19) | public static void main(String[] args) {
FILE: code/chapter1_4_Analysis_of_Algorithms/Stopwatch.java
class Stopwatch (line 3) | public class Stopwatch {
method Stopwatch (line 5) | public Stopwatch() {
method elapsedTime (line 8) | public double elapsedTime() {
FILE: code/chapter1_4_Analysis_of_Algorithms/StopwatchTest.java
class StopwatchTest (line 6) | public class StopwatchTest {
method main (line 8) | public static void main(String[] args) {
FILE: code/chapter1_4_Analysis_of_Algorithms/ThreeSum.java
class ThreeSum (line 6) | public class ThreeSum {
method count (line 8) | public static int count(int[] a) {
method main (line 19) | public static void main(String[] args) {
FILE: code/chapter1_5_Case_Study_Union_Find/UF.java
class UF (line 6) | public class UF {
method UF (line 10) | public UF(int N) {
method count (line 18) | public int count() {
method connected (line 22) | public boolean connected(int p, int q) {
method find (line 48) | private int find(int p) {
method union (line 55) | private void union(int p, int q) {
method main (line 67) | public static void main(String[] args) {
FILE: code/chapter1_5_Case_Study_Union_Find/WeightedQuickUnionUF.java
class WeightedQuickUnionUF (line 7) | public class WeightedQuickUnionUF {
method WeightedQuickUnionUF (line 12) | public WeightedQuickUnionUF(int N) {
method count (line 22) | public int count() {
method connected (line 26) | public boolean connected(int p, int q) {
method find (line 30) | public int find(int p) {
method union (line 37) | public void union(int p, int q) {
FILE: code/chapter2_1_Elementary_Sorts/Insertion.java
class Insertion (line 9) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method sort (line 11) | public static void sort(Comparable[] a) {
method less (line 22) | private static boolean less(Comparable v, Comparable w) {
method exch (line 27) | private static void exch(Comparable[] a, int i, int j) {
method show (line 34) | private static void show(Comparable[] a) {
method isSorted (line 41) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_1_Elementary_Sorts/Selection.java
class Selection (line 9) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method sort (line 11) | public static void sort(Comparable[] a) {
method less (line 24) | private static boolean less(Comparable v, Comparable w) {
method exch (line 29) | private static void exch(Comparable[] a, int i, int j) {
method show (line 36) | private static void show(Comparable[] a) {
method isSorted (line 43) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_1_Elementary_Sorts/Shell.java
class Shell (line 9) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method sort (line 11) | public static void sort(Comparable[] a) {
method less (line 28) | private static boolean less(Comparable v, Comparable w) {
method exch (line 33) | private static void exch(Comparable[] a, int i, int j) {
method show (line 40) | private static void show(Comparable[] a) {
method isSorted (line 47) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_1_Elementary_Sorts/SortCompare.java
class SortCompare (line 11) | @SuppressWarnings({"rawtypes"})
method time (line 13) | public static double time(String alg, Comparable[] a) {
method timeRandomInput (line 30) | public static double timeRandomInput(String alg, int N, int T) {
method main (line 43) | public static void main(String[] args) {
FILE: code/chapter2_2_Mergesort/Merge.java
class Merge (line 9) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method sort (line 13) | public static void sort(Comparable[] a) {
method sort (line 18) | private static void sort(Comparable[] a, int lo, int hi) {
method merge (line 29) | public static void merge(Comparable[] a, int lo, int mid, int hi) {
method less (line 47) | private static boolean less(Comparable v, Comparable w) {
method exch (line 52) | private static void exch(Comparable[] a, int i, int j) {
method show (line 59) | private static void show(Comparable[] a) {
method isSorted (line 66) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_2_Mergesort/MergeBU.java
class MergeBU (line 9) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method sort (line 13) | public static void sort(Comparable[] a) {
method merge (line 22) | public static void merge(Comparable[] a, int lo, int mid, int hi) {
method less (line 40) | private static boolean less(Comparable v, Comparable w) {
method exch (line 45) | private static void exch(Comparable[] a, int i, int j) {
method show (line 52) | private static void show(Comparable[] a) {
method isSorted (line 59) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_3_Quicksort/Ex25.java
class Ex25 (line 14) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method main (line 16) | public static void main(String[] args) {
method sort (line 32) | public static void sort(Comparable[] a, int M) {
method sort (line 37) | private static void sort(Comparable[] a, int lo, int hi, int M) {
method insertSort (line 47) | private static void insertSort(Comparable[] a, int lo, int hi) {
method partition (line 55) | private static int partition(Comparable[] a, int lo, int hi) {
method less (line 75) | private static boolean less(Comparable v, Comparable w) {
method exch (line 80) | private static void exch(Comparable[] a, int i, int j) {
method show (line 87) | private static void show(Comparable[] a) {
method isSorted (line 94) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_3_Quicksort/Quick.java
class Quick (line 10) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method sort (line 12) | public static void sort(Comparable[] a) {
method sort (line 17) | private static void sort(Comparable[] a, int lo, int hi) {
method partition (line 25) | private static int partition(Comparable[] a, int lo, int hi) {
method less (line 45) | private static boolean less(Comparable v, Comparable w) {
method exch (line 50) | private static void exch(Comparable[] a, int i, int j) {
method show (line 57) | private static void show(Comparable[] a) {
method isSorted (line 64) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_3_Quicksort/Quick3way.java
class Quick3way (line 10) | @SuppressWarnings({"rawtypes", "unused", "unchecked"})
method sort (line 12) | public static void sort(Comparable[] a) {
method sort (line 17) | private static void sort(Comparable[] a, int lo, int hi) {
method partition (line 35) | private static int partition(Comparable[] a, int lo, int hi) {
method less (line 55) | private static boolean less(Comparable v, Comparable w) {
method exch (line 60) | private static void exch(Comparable[] a, int i, int j) {
method show (line 67) | private static void show(Comparable[] a) {
method isSorted (line 74) | public static boolean isSorted(Comparable[] a) {
FILE: code/chapter2_4_Priority_Queues/MaxPQ.java
class MaxPQ (line 8) | public class MaxPQ<Key extends Comparable<Key>> {
method MaxPQ (line 13) | @SuppressWarnings("unchecked")
method insert (line 19) | void insert(Key v) {
method delMax (line 25) | public Key delMax() {
method isEmpty (line 33) | boolean isEmpty() { // 返回队列是否为空
method size (line 37) | int size() { // 返回优先队列中的元素个数
method less (line 41) | private boolean less(int i, int j) {
method exch (line 45) | private void exch(int i, int j) {
method swim (line 52) | private void swim(int k) {
method sink (line 60) | private void sink(int k) {
FILE: code/chapter2_4_Priority_Queues/TopM.java
class TopM (line 8) | public class TopM {
method main (line 9) | public static void main(String[] args) {
FILE: code/chapter3_1_Symbol_Tables/BinarySearchST.java
class BinarySearchST (line 5) | @SuppressWarnings("unchecked")
method BinarySearchST (line 10) | public BinarySearchST(int capacity) {
method resize (line 15) | private void resize(int max) {
method size (line 27) | public int size() {
method get (line 31) | public Value get(Key key) {
method isEmpty (line 41) | public boolean isEmpty() {
method rank (line 45) | public int rank(Key key) {
method put (line 60) | public void put(Key key, Value val) {
method min (line 78) | public Key min() {
method max (line 82) | public Key max() {
method select (line 86) | public Key select(int k) {
method ceiling (line 90) | public Key ceiling(Key key) {
method delete (line 99) | public Key delete(Key key) {
method keys (line 116) | public Iterable<Key> keys(Key lo, Key hi) {
method contains (line 125) | public boolean contains(Key key) {
FILE: code/chapter3_1_Symbol_Tables/FrequencyCounter.java
class FrequencyCounter (line 11) | public class FrequencyCounter {
method main (line 12) | public static void main(String[] args) {
FILE: code/chapter3_1_Symbol_Tables/SequentialSearchST.java
class SequentialSearchST (line 3) | public class SequentialSearchST<Key, Value>{
class Node (line 5) | private class Node {
method Node (line 9) | public Node(Key key, Value val, Node next) {
method get (line 16) | public Value get(Key key) {
method put (line 24) | public void put(Key key, Value val) {
FILE: code/chapter3_2_Binary_Search_Trees/BST.java
class BST (line 5) | public class BST<Key extends Comparable<Key>, Value> {
class Node (line 8) | private class Node {
method Node (line 14) | public Node(Key key, Value val, int N) {
method size (line 21) | public int size() {
method size (line 25) | private int size(Node x) {
method get (line 32) | public Value get(Key key) {
method get (line 36) | private Value get(Node x, Key key) {
method put (line 49) | public void put(Key key, Value val) {
method put (line 54) | private Node put(Node x, Key key, Value val) {
method min (line 70) | public Key min() {
method min (line 74) | private Node min(Node x) {
method max (line 80) | public Key max() {
method max (line 84) | private Node max(Node x) {
method floor (line 90) | public Key floor(Key key) {
method floor (line 97) | private Node floor(Node x, Key key) {
method select (line 112) | public Key select(int k) {
method select (line 116) | private Node select(Node x, int k) {
method rank (line 129) | public int rank(Key key) {
method rank (line 133) | private int rank(Key key, Node x) {
method deleteMin (line 146) | public void deleteMin() {
method deleteMin (line 150) | private Node deleteMin(Node x) {
method delete (line 158) | public void delete(Key key) {
method delete (line 162) | private Node delete(Node x, Key key) {
method keys (line 184) | public Iterable<Key> keys() {
method keys (line 188) | public Iterable<Key> keys(Key lo, Key hi) {
method keys (line 194) | private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {
FILE: code/chapter3_4_Hash_Tables/LinearProbingHashST.java
class LinearProbingHashST (line 5) | @SuppressWarnings("unchecked")
method LinearProbingHashST (line 12) | public LinearProbingHashST() {
method LinearProbingHashST (line 17) | public LinearProbingHashST(int cap) {
method size (line 23) | public int size() {
method hash (line 27) | private int hash(Key key) {
method resize (line 31) | private void resize(int cap) {
method put (line 42) | public void put(Key key, Value val) {
method get (line 56) | public Value get(Key key) {
method contains (line 63) | public boolean contains(Key key) {
method delete (line 67) | public void delete(Key key) {
method keys (line 90) | public Iterable<Key> keys() {
FILE: code/chapter3_4_Hash_Tables/SeparateChainingHashST.java
class SeparateChainingHashST (line 8) | @SuppressWarnings("unchecked")
method SeparateChainingHashST (line 14) | public SeparateChainingHashST() {
method SeparateChainingHashST (line 18) | public SeparateChainingHashST(int M) {
method hash (line 26) | private int hash(Key key) {
method get (line 30) | public Value get(Key key) {
method put (line 34) | public void put(Key key, Value val) {
method keys (line 38) | public Iterable<Key> keys() {
FILE: code/chapter3_5_Searching_Applications/SparseVector.java
class SparseVector (line 9) | public class SparseVector {
method SparseVector (line 11) | public SparseVector() {
method size (line 14) | public int size() {
method put (line 17) | public void put(int i, double x) {
method get (line 20) | public double get(int i) {
method dot (line 25) | public double dot(double[] that) {
FILE: code/chapter3_5_Searching_Applications/WhiteFilter.java
class WhiteFilter (line 13) | public class WhiteFilter {
method main (line 14) | public static void main(String[] args) {
FILE: code/chapter4_1_Undirected_Graphs/BreadthFirstPaths.java
class BreadthFirstPaths (line 6) | public class BreadthFirstPaths {
method BreadthFirstPaths (line 11) | public BreadthFirstPaths(Graph G, int s) {
method bfs (line 18) | private void bfs(Graph G, int s) {
method hasPathTo (line 33) | public boolean hasPathTo(int v) {
method pathTo (line 37) | public Iterable<Integer> pathTo(int v) {
FILE: code/chapter4_1_Undirected_Graphs/CC.java
class CC (line 7) | public class CC {
method CC (line 12) | public CC(Graph G) {
method dfs (line 22) | private void dfs(Graph G, int v) {
method connected (line 30) | public boolean connected(int v, int w) {
method id (line 34) | public int id(int v) {
method count (line 38) | public int count() {
FILE: code/chapter4_1_Undirected_Graphs/Cycle.java
class Cycle (line 7) | public class Cycle {
method Cycle (line 10) | public Cycle(Graph G) {
method dfs (line 17) | private void dfs(Graph G, int v, int u) {
method hasCycle (line 27) | public boolean hasCycle() {
FILE: code/chapter4_1_Undirected_Graphs/DegreesOfSeparation.java
class DegreesOfSeparation (line 10) | public class DegreesOfSeparation {
method main (line 12) | public static void main(String[] args) {
FILE: code/chapter4_1_Undirected_Graphs/DepthFirstPaths.java
class DepthFirstPaths (line 10) | public class DepthFirstPaths {
method DepthFirstPaths (line 15) | public DepthFirstPaths(Graph G, int s) {
method dfs (line 22) | private void dfs(Graph G, int v) {
method hasPathTo (line 31) | public boolean hasPathTo(int v) {
method pathTo (line 35) | public Iterable<Integer> pathTo(int v) {
FILE: code/chapter4_1_Undirected_Graphs/DepthFirstSearch.java
class DepthFirstSearch (line 3) | public class DepthFirstSearch {
method DepthFirstSearch (line 7) | public DepthFirstSearch(Graph G, int s) {
method dfs (line 12) | private void dfs(Graph G, int v) {
method marked (line 20) | public boolean marked(int w) {
method count (line 24) | public int count() {
FILE: code/chapter4_1_Undirected_Graphs/Graph.java
class Graph (line 6) | public class Graph {
method Graph (line 11) | @SuppressWarnings("unchecked")
method Graph (line 19) | public Graph(In in) {
method V (line 29) | public int V() {
method E (line 32) | public int E() {
method addEdge (line 35) | public void addEdge(int v, int w) {
method adj (line 40) | public Iterable<Integer> adj(int v) {
FILE: code/chapter4_1_Undirected_Graphs/SymbolGraph.java
class SymbolGraph (line 6) | public class SymbolGraph {
method SymbolGraph (line 12) | public SymbolGraph(String filename, String delim) {
method contains (line 37) | boolean contains(String key) {
method index (line 42) | int index(String key) {
method name (line 47) | String name(int v) {
method G (line 52) | Graph G() {
FILE: code/chapter4_1_Undirected_Graphs/TestCC.java
class TestCC (line 11) | public class TestCC {
method main (line 12) | @SuppressWarnings("unchecked")
FILE: code/chapter4_1_Undirected_Graphs/TestPaths.java
class TestPaths (line 10) | public class TestPaths {
method main (line 12) | public static void main(String[] args) {
FILE: code/chapter4_1_Undirected_Graphs/TestSearch.java
class TestSearch (line 6) | public class TestSearch {
method main (line 8) | public static void main(String[] args) {
FILE: code/chapter4_1_Undirected_Graphs/TestSymbolGraph.java
class TestSymbolGraph (line 6) | public class TestSymbolGraph {
method main (line 8) | public static void main(String[] args) {
FILE: code/chapter4_1_Undirected_Graphs/TwoColor.java
class TwoColor (line 7) | public class TwoColor {
method TwoColor (line 11) | public TwoColor(Graph G) {
method dfs (line 19) | private void dfs(Graph G, int v) {
method isBipartite (line 30) | public boolean isBipartite() {
FILE: code/chapter4_2_Directed_Graphs/DepthFirstOrder.java
class DepthFirstOrder (line 6) | public class DepthFirstOrder {
method DepthFirstOrder (line 12) | public DepthFirstOrder(Digraph G) {
method dfs (line 23) | private void dfs(Digraph G, int v) {
method pre (line 34) | public Iterable<Integer> pre() {
method post (line 38) | public Iterable<Integer> post() {
method reversePost (line 42) | public Iterable<Integer> reversePost() {
FILE: code/chapter4_2_Directed_Graphs/Digraph.java
class Digraph (line 6) | public class Digraph {
method Digraph (line 12) | @SuppressWarnings("unchecked")
method Digraph (line 22) | public Digraph(In in) { // 从输入流 in 中读取一幅有向图
method V (line 33) | public int V() { // 顶点总数
method E (line 37) | public int E() { // 边的总数
method addEdge (line 41) | void addEdge(int v, int w) { // 向有向图中添加一条边 v -> w
method adj (line 46) | public Iterable<Integer> adj(int v) { // 由 v 指出的边所连接的所有顶点
method reverse (line 50) | public Digraph reverse() { // 该图的反向图
FILE: code/chapter4_2_Directed_Graphs/DirectedCycle.java
class DirectedCycle (line 5) | public class DirectedCycle {
method DirectedCycle (line 11) | public DirectedCycle(Digraph G) {
method dfs (line 21) | private void dfs(Digraph G, int v) {
method hasCycle (line 41) | public boolean hasCycle() {
method cycle (line 45) | public Iterable<Integer> cycle() {
FILE: code/chapter4_2_Directed_Graphs/DirectedDFS.java
class DirectedDFS (line 10) | public class DirectedDFS {
method DirectedDFS (line 13) | public DirectedDFS(Digraph G, int s) {
method DirectedDFS (line 18) | public DirectedDFS(Digraph G, Iterable<Integer> sources) {
method dfs (line 25) | private void dfs(Digraph G, int v) {
method marked (line 32) | public boolean marked(int v) {
method main (line 36) | public static void main(String[] args) {
FILE: code/chapter4_2_Directed_Graphs/KosarajuSCC.java
class KosarajuSCC (line 6) | public class KosarajuSCC {
method KosarajuSCC (line 11) | public KosarajuSCC(Digraph G) {
method dfs (line 22) | private void dfs(Digraph G, int v) {
method stronglyConnected (line 30) | public boolean stronglyConnected(int v, int w) {
method id (line 34) | public int id(int v) {
method count (line 38) | public int count() {
FILE: code/chapter4_2_Directed_Graphs/SymbolDigraph.java
class SymbolDigraph (line 6) | public class SymbolDigraph {
method SymbolDigraph (line 12) | public SymbolDigraph(String filename, String delim) {
method contains (line 37) | boolean contains(String key) {
method index (line 42) | int index(String key) {
method name (line 47) | public String name(int v) {
method G (line 52) | public Digraph G() {
FILE: code/chapter4_2_Directed_Graphs/Topological.java
class Topological (line 8) | public class Topological {
method Topological (line 11) | public Topological(Digraph G) {
method order (line 19) | public Iterable<Integer> order() {
method isDAG (line 23) | public boolean isDAG() {
method main (line 27) | public static void main(String[] args) {
FILE: code/chapter4_2_Directed_Graphs/TransitiveClosure.java
class TransitiveClosure (line 6) | public class TransitiveClosure {
method TransitiveClosure (line 8) | public TransitiveClosure(Digraph G) {
method reachable (line 14) | public boolean reachable(int v, int w) {
FILE: code/chapter4_3_Minimum_Spanning_Tree/Edge.java
class Edge (line 6) | public class Edge implements Comparable<Edge> {
method Edge (line 11) | public Edge(int v, int w, double weight) {
method weight (line 17) | public double weight() {
method either (line 22) | public int either() {
method other (line 27) | public int other(int vertex) {
method compareTo (line 36) | public int compareTo(Edge that) {
method toString (line 45) | public String toString() {
FILE: code/chapter4_3_Minimum_Spanning_Tree/EdgeWeightedGraph.java
class EdgeWeightedGraph (line 9) | public class EdgeWeightedGraph {
method EdgeWeightedGraph (line 14) | @SuppressWarnings("unchecked")
method EdgeWeightedGraph (line 23) | public EdgeWeightedGraph(In in) {
method V (line 36) | public int V() {
method E (line 40) | public int E() {
method addEdge (line 44) | public void addEdge(Edge e) {
method adj (line 52) | public Iterable<Edge> adj(int v) {
method edges (line 57) | public Iterable<Edge> edges() {
FILE: code/chapter4_3_Minimum_Spanning_Tree/KruskalMST.java
class KruskalMST (line 6) | public class KruskalMST {
method KruskalMST (line 9) | public KruskalMST(EdgeWeightedGraph G) {
method edges (line 26) | public Iterable<Edge> edges() {
method weight (line 30) | public double weight() {
FILE: code/chapter4_3_Minimum_Spanning_Tree/LazyPrimMST.java
class LazyPrimMST (line 11) | public class LazyPrimMST {
method LazyPrimMST (line 16) | public LazyPrimMST(EdgeWeightedGraph G) {
method visit (line 37) | private void visit(EdgeWeightedGraph G, int v) {
method edges (line 45) | public Iterable<Edge> edges() {
method weight (line 49) | public double weight() {
FILE: code/chapter4_3_Minimum_Spanning_Tree/PrimMST.java
class PrimMST (line 8) | public class PrimMST {
method PrimMST (line 14) | public PrimMST(EdgeWeightedGraph G) {
method visit (line 28) | private void visit(EdgeWeightedGraph G, int v) {
method edges (line 47) | public Iterable<Edge> edges() {
method weight (line 51) | public double weight() {
FILE: code/chapter4_3_Minimum_Spanning_Tree/TestMST.java
class TestMST (line 9) | public class TestMST {
method main (line 11) | public static void main(String[] args) {
FILE: code/chapter4_3_Minimum_Spanning_Tree/UF.java
class UF (line 6) | public class UF {
method UF (line 10) | public UF(int N) {
method count (line 18) | public int count() {
method connected (line 22) | public boolean connected(int p, int q) {
method find (line 48) | private int find(int p) {
method union (line 55) | public void union(int p, int q) {
method main (line 67) | public static void main(String[] args) {
FILE: code/chapter4_4_Shortest_Paths/DijkstraSP.java
class DijkstraSP (line 10) | public class DijkstraSP implements SP {
method DijkstraSP (line 15) | public DijkstraSP(EdgeWeightedDigraph G, int s) {
method relax (line 28) | private void relax(EdgeWeightedDigraph G, int v) {
method distTo (line 42) | public double distTo(int v) {
method hasPathTo (line 46) | public boolean hasPathTo(int v) {
method pathTo (line 50) | public Iterable<DirectedEdge> pathTo(int v) {
FILE: code/chapter4_4_Shortest_Paths/DirectedEdge.java
class DirectedEdge (line 7) | public class DirectedEdge {
method DirectedEdge (line 12) | public DirectedEdge(int v, int w, double weight) {
method weight (line 18) | public double weight() {
method from (line 22) | public int from() {
method to (line 26) | public int to() {
method toString (line 30) | public String toString() {
FILE: code/chapter4_4_Shortest_Paths/EdgeWeightedDigraph.java
class EdgeWeightedDigraph (line 10) | public class EdgeWeightedDigraph {
method EdgeWeightedDigraph (line 15) | @SuppressWarnings("unchecked")
method EdgeWeightedDigraph (line 24) | public EdgeWeightedDigraph(In in) {
method V (line 33) | public int V() {
method E (line 37) | public int E() {
method addEdge (line 41) | public void addEdge(DirectedEdge e) {
method adj (line 46) | public Iterable<DirectedEdge> adj(int v) {
method edges (line 50) | public Iterable<DirectedEdge> edges() {
FILE: code/chapter4_4_Shortest_Paths/SP.java
type SP (line 7) | public interface SP {
method distTo (line 9) | double distTo(int v);
method hasPathTo (line 11) | boolean hasPathTo(int v);
method pathTo (line 13) | Iterable<DirectedEdge> pathTo(int v);
FILE: code/chapter4_4_Shortest_Paths/TestSP.java
class TestSP (line 10) | public class TestSP {
method main (line 11) | public static void main(String[] args) {
FILE: code/chapter5_3_Substring_Search/BoyerMoore.java
class BoyerMoore (line 9) | public class BoyerMoore {
method BoyerMoore (line 15) | public BoyerMoore(String pat) {
method search (line 27) | public int search(String txt) {
method main (line 47) | public static void main(String[] args) {
FILE: code/chapter5_3_Substring_Search/KMP.java
class KMP (line 9) | public class KMP {
method KMP (line 13) | public KMP(String pat) {
method search (line 28) | public int search(String txt) {
method main (line 38) | public static void main(String[] args) {
FILE: code/chapter5_3_Substring_Search/RabinKarp.java
class RabinKarp (line 12) | public class RabinKarp {
method RabinKarp (line 20) | public RabinKarp(String pat) {
method check (line 30) | public boolean check(int i) { // 蒙特卡洛算法直接返回 true
method hash (line 34) | private long hash(String key, int M) { // Horner 方法计算 key[0..M-1] 的散列值
method search (line 41) | private int search(String txt) {
method longRandomPrime (line 59) | private static long longRandomPrime() {
method main (line 64) | public static void main(String[] args) {
FILE: code/chapter6_3_Suffix_Arrays/KWIC.java
class KWIC (line 12) | public class KWIC {
method main (line 13) | public static void main(String[] args) {
FILE: code/chapter6_3_Suffix_Arrays/LRS.java
class LRS (line 10) | public class LRS {
method main (line 11) | public static void main(String[] args) {
FILE: code/chapter6_3_Suffix_Arrays/SuffixArray.java
class SuffixArray (line 9) | public class SuffixArray {
method SuffixArray (line 13) | public SuffixArray(String s) {
method length (line 21) | public int length() {
method select (line 25) | public String select(int i) {
method index (line 29) | public int index(int i) {
method lcp (line 33) | private static int lcp(String s, String t) {
method lcp (line 41) | public int lcp(int i) {
method rank (line 45) | public int rank(String key) {
Condensed preview — 169 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (640K chars).
[
{
"path": ".gitignore",
"chars": 272,
"preview": "# Compiled class file\n*.class\n\n# Log file\n*.log\n\n# BlueJ files\n*.ctxt\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Packa"
},
{
"path": "README.md",
"chars": 3315,
"preview": "# 《算法(第4版)》笔记及代码\n\n[](http://kyonhuang.top)\n\n#"
},
{
"path": "code/README.md",
"chars": 17007,
"preview": "# 代码目录\n\n\n### algs4\n\n* [Alphabet.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Alphabet.ja"
},
{
"path": "code/algs4/Alphabet.java",
"chars": 9040,
"preview": "/******************************************************************************\n * Compilation: javac Alphabet.java\n *"
},
{
"path": "code/algs4/Bag.java",
"chars": 5050,
"preview": "/******************************************************************************\n * Compilation: javac Bag.java\n * Exe"
},
{
"path": "code/algs4/BinarySearch.java",
"chars": 4609,
"preview": "/******************************************************************************\n * Compilation: javac BinarySearch.jav"
},
{
"path": "code/algs4/BinaryStdIn.java",
"chars": 10597,
"preview": "/******************************************************************************\n * Compilation: javac BinaryStdIn.java"
},
{
"path": "code/algs4/BinaryStdOut.java",
"chars": 9516,
"preview": "/******************************************************************************\n * Compilation: javac BinaryStdOut.jav"
},
{
"path": "code/algs4/Counter.java",
"chars": 4361,
"preview": "/******************************************************************************\n * Compilation: javac Counter.java\n * "
},
{
"path": "code/algs4/DepthFirstOrder.java",
"chars": 9347,
"preview": "///******************************************************************************\n// * Compilation: javac DepthFirstOr"
},
{
"path": "code/algs4/Draw.java",
"chars": 47217,
"preview": "/******************************************************************************\n * Compilation: javac Draw.java\n * Ex"
},
{
"path": "code/algs4/DrawListener.java",
"chars": 2518,
"preview": "/******************************************************************************\n * Compilation: javac DrawListener.jav"
},
{
"path": "code/algs4/Heap.java",
"chars": 4803,
"preview": "/******************************************************************************\n * Compilation: javac Heap.java\n * Ex"
},
{
"path": "code/algs4/HexDump.java",
"chars": 3624,
"preview": "/******************************************************************************\n * Compilation: javac HexDump.java\n * "
},
{
"path": "code/algs4/In.java",
"chars": 24395,
"preview": "/******************************************************************************\n * Compilation: javac In.java\n * Exec"
},
{
"path": "code/algs4/IndexMinPQ.java",
"chars": 14183,
"preview": "/******************************************************************************\n * Compilation: javac IndexMinPQ.java\n"
},
{
"path": "code/algs4/Interval1D.java",
"chars": 9131,
"preview": "/******************************************************************************\n * Compilation: javac Interval1D.java\n"
},
{
"path": "code/algs4/Interval2D.java",
"chars": 5959,
"preview": "/******************************************************************************\n * Compilation: javac Interval2D.java\n"
},
{
"path": "code/algs4/MinPQ.java",
"chars": 10057,
"preview": "/******************************************************************************\n * Compilation: javac MinPQ.java\n * E"
},
{
"path": "code/algs4/Out.java",
"chars": 8784,
"preview": "/******************************************************************************\n * Compilation: javac Out.java\n * Exe"
},
{
"path": "code/algs4/Particle.java",
"chars": 9220,
"preview": "/******************************************************************************\n * Compilation: javac Particle.java\n *"
},
{
"path": "code/algs4/Picture.java",
"chars": 13751,
"preview": "/******************************************************************************\n * Compilation: javac Picture.java\n * "
},
{
"path": "code/algs4/PictureDump.java",
"chars": 3264,
"preview": "/******************************************************************************\n * Compilation: javac PictureDump.java"
},
{
"path": "code/algs4/Point2D.java",
"chars": 13070,
"preview": "/******************************************************************************\n * Compilation: javac Point2D.java\n * "
},
{
"path": "code/algs4/Queue.java",
"chars": 6556,
"preview": "/******************************************************************************\n * Compilation: javac Queue.java\n * E"
},
{
"path": "code/algs4/SET.java",
"chars": 12171,
"preview": "/******************************************************************************\n * Compilation: javac SET.java\n * Exe"
},
{
"path": "code/algs4/ST.java",
"chars": 9678,
"preview": "/******************************************************************************\n * Compilation: javac ST.java\n * Exec"
},
{
"path": "code/algs4/Stack.java",
"chars": 6708,
"preview": "/******************************************************************************\n * Compilation: javac Stack.java\n * E"
},
{
"path": "code/algs4/StdDraw.java",
"chars": 74286,
"preview": "/******************************************************************************\n * Compilation: javac StdDraw.java\n * "
},
{
"path": "code/algs4/StdIn.java",
"chars": 22220,
"preview": "/******************************************************************************\n * Compilation: javac StdIn.java\n * E"
},
{
"path": "code/algs4/StdOut.java",
"chars": 9691,
"preview": "/******************************************************************************\n * Compilation: javac StdOut.java\n * "
},
{
"path": "code/algs4/StdRandom.java",
"chars": 20539,
"preview": "/******************************************************************************\n * Compilation: javac StdRandom.java\n "
},
{
"path": "code/chapter1_1_Programming_Model/BinarySearch.java",
"chars": 839,
"preview": "package chapter1_1_Programming_Model;\n\nimport java.util.Arrays;\nimport algs4.*;\n\n/**\n * 二分查找\n * @author huang\n */\npublic"
},
{
"path": "code/chapter1_1_Programming_Model/BouncingBall.java",
"chars": 1299,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdDraw;\n\npublic class BouncingBall {\n\n public static void main(S"
},
{
"path": "code/chapter1_1_Programming_Model/Ex1.java",
"chars": 284,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex1 {\n\n public static void main(String[] ar"
},
{
"path": "code/chapter1_1_Programming_Model/Ex10.java",
"chars": 312,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex10 {\n\n public static void main(String[] a"
},
{
"path": "code/chapter1_1_Programming_Model/Ex11.java",
"chars": 978,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class Ex11 {\n\n public sta"
},
{
"path": "code/chapter1_1_Programming_Model/Ex13.java",
"chars": 1061,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class Ex13 {\n\n public sta"
},
{
"path": "code/chapter1_1_Programming_Model/Ex14.java",
"chars": 463,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex14 {\n\n public static void main(String[] a"
},
{
"path": "code/chapter1_1_Programming_Model/Ex15.java",
"chars": 676,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex15 {\n\n public static void main(String[] a"
},
{
"path": "code/chapter1_1_Programming_Model/Ex19.java",
"chars": 509,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex19 {\n \n static final int M = 100;\n "
},
{
"path": "code/chapter1_1_Programming_Model/Ex2.java",
"chars": 290,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex2 {\n\n public static void main(String[] ar"
},
{
"path": "code/chapter1_1_Programming_Model/Ex20.java",
"chars": 333,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex20 {\n\n public static void main(String[] a"
},
{
"path": "code/chapter1_1_Programming_Model/Ex3.java",
"chars": 388,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class Ex3 {\n public static vo"
},
{
"path": "code/chapter1_1_Programming_Model/Ex30.java",
"chars": 855,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex30 {\n\n public static void main(String[] a"
},
{
"path": "code/chapter1_1_Programming_Model/Ex31.java",
"chars": 1339,
"preview": "package chapter1_1_Programming_Model;\n\nimport java.awt.Color;\n\nimport algs4.StdDraw;\nimport algs4.StdRandom;\n\npublic cla"
},
{
"path": "code/chapter1_1_Programming_Model/Ex32.java",
"chars": 1030,
"preview": "package chapter1_1_Programming_Model;\n\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\nimport algs4.StdDraw;\n\npub"
},
{
"path": "code/chapter1_1_Programming_Model/Ex6.java",
"chars": 295,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex6 {\n public static void main(String[] arg"
},
{
"path": "code/chapter1_1_Programming_Model/Ex7a.java",
"chars": 287,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex7a {\n\n public static void main(String[] a"
},
{
"path": "code/chapter1_1_Programming_Model/Ex7b.java",
"chars": 284,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex7b {\n public static void main(String[] ar"
},
{
"path": "code/chapter1_1_Programming_Model/Ex7c.java",
"chars": 302,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex7c {\n\n public static void main(String[] a"
},
{
"path": "code/chapter1_1_Programming_Model/Ex8.java",
"chars": 240,
"preview": "package chapter1_1_Programming_Model;\n\npublic class Ex8 {\n\n public static void main(String[] args) {\n \n "
},
{
"path": "code/chapter1_1_Programming_Model/Ex9.java",
"chars": 359,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex9 {\n\n public static void main(String[] ar"
},
{
"path": "code/chapter1_1_Programming_Model/RightTriangle.java",
"chars": 380,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdDraw;\n\npublic class RightTriangle {\n\n public static void main("
},
{
"path": "code/chapter1_1_Programming_Model/Sattolo.java",
"chars": 627,
"preview": "package chapter1_1_Programming_Model;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class Sattolo {\n \n private"
},
{
"path": "code/chapter1_1_Programming_Model/StdDrawTest.java",
"chars": 728,
"preview": "package chapter1_1_Programming_Model;\n\nimport java.util.Arrays;\nimport algs4.*;\n\npublic class StdDrawTest {\n\tpublic stat"
},
{
"path": "code/chapter1_2_Data_Abstraction/Accumulator.java",
"chars": 369,
"preview": "package chapter1_2_Data_Abstraction;\n\npublic class Accumulator {\n private double total;\n private int N;\n public"
},
{
"path": "code/chapter1_2_Data_Abstraction/AccumulatorTest.java",
"chars": 388,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class AccumulatorTest {\n\n "
},
{
"path": "code/chapter1_2_Data_Abstraction/Cat.java",
"chars": 477,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.In;\nimport algs4.Out;\n\npublic class Cat {\n\n public static void mai"
},
{
"path": "code/chapter1_2_Data_Abstraction/Date.java",
"chars": 950,
"preview": "package chapter1_2_Data_Abstraction;\n\npublic class Date {\n private final int month;\n private final int day;\n pr"
},
{
"path": "code/chapter1_2_Data_Abstraction/Flips.java",
"chars": 667,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class F"
},
{
"path": "code/chapter1_2_Data_Abstraction/FlipsMax.java",
"chars": 802,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class F"
},
{
"path": "code/chapter1_2_Data_Abstraction/Interval2DTest.java",
"chars": 1074,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.Interval1D;\nimport algs4.Interval2D;\nimport alg"
},
{
"path": "code/chapter1_2_Data_Abstraction/Rolls.java",
"chars": 631,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class R"
},
{
"path": "code/chapter1_2_Data_Abstraction/StaticSETofInts.java",
"chars": 810,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport java.util.Arrays;\n\npublic class StaticSETofInts {\n private int[] a;\n "
},
{
"path": "code/chapter1_2_Data_Abstraction/VisualAccumulator.java",
"chars": 733,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.StdDraw;\n\npublic class VisualAccumulator {\n private double total;\n"
},
{
"path": "code/chapter1_2_Data_Abstraction/VisualAccumulatorTest.java",
"chars": 412,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class VisualAccumulatorTest {"
},
{
"path": "code/chapter1_2_Data_Abstraction/WhiteList.java",
"chars": 468,
"preview": "package chapter1_2_Data_Abstraction;\n\nimport algs4.In;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class WhiteList "
},
{
"path": "code/chapter1_2_Data_Abstraction/in1.txt",
"chars": 7,
"preview": "This is"
},
{
"path": "code/chapter1_2_Data_Abstraction/in2.txt",
"chars": 12,
"preview": "a tiny\ntest."
},
{
"path": "code/chapter1_3_Bags_Queues_Stacks/ResizingArrayStack.java",
"chars": 1193,
"preview": "package chapter1_3_Bags_Queues_Stacks;\n\nimport java.util.Iterator;\n\npublic class ResizingArrayStack<Item> implements Ite"
},
{
"path": "code/chapter1_4_Analysis_of_Algorithms/DoublingRatio.java",
"chars": 804,
"preview": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class DoublingRatio {\n\n"
},
{
"path": "code/chapter1_4_Analysis_of_Algorithms/DoublingTest.java",
"chars": 704,
"preview": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class DoublingTest {\n "
},
{
"path": "code/chapter1_4_Analysis_of_Algorithms/Stopwatch.java",
"chars": 302,
"preview": "package chapter1_4_Analysis_of_Algorithms;\n\npublic class Stopwatch {\n private final long start;\n public Stopwatch("
},
{
"path": "code/chapter1_4_Analysis_of_Algorithms/StopwatchTest.java",
"chars": 530,
"preview": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class StopwatchTest {\n\n"
},
{
"path": "code/chapter1_4_Analysis_of_Algorithms/ThreeSum.java",
"chars": 558,
"preview": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.In;\nimport algs4.StdOut;\n\npublic class ThreeSum {\n \n publ"
},
{
"path": "code/chapter1_5_Case_Study_Union_Find/UF.java",
"chars": 1889,
"preview": "package chapter1_5_Case_Study_Union_Find;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class UF {\n private int[]"
},
{
"path": "code/chapter1_5_Case_Study_Union_Find/WeightedQuickUnionUF.java",
"chars": 1175,
"preview": "package chapter1_5_Case_Study_Union_Find;\n\n/**\n * 加权 quick-union 算法\n * @author huang\n */\npublic class WeightedQuickUnion"
},
{
"path": "code/chapter2_1_Elementary_Sorts/Insertion.java",
"chars": 1183,
"preview": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\n\n/**\n * 插入排序\n * @author huang\n */\n@SuppressWarnings({\"rawtype"
},
{
"path": "code/chapter2_1_Elementary_Sorts/Selection.java",
"chars": 1216,
"preview": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\n\n/**\n * 选择排序\n * @author huang\n */\n@SuppressWarnings({\"rawtype"
},
{
"path": "code/chapter2_1_Elementary_Sorts/Shell.java",
"chars": 1360,
"preview": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\n\n/**\n * 希尔排序\n * @author huang\n */\n@SuppressWarnings({\"rawtype"
},
{
"path": "code/chapter2_1_Elementary_Sorts/SortCompare.java",
"chars": 1651,
"preview": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\nimport chapter1_4_Analysis_of_Algorit"
},
{
"path": "code/chapter2_2_Mergesort/Merge.java",
"chars": 2007,
"preview": "package chapter2_2_Mergesort;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 自顶向下的归并排序\n */\n@SuppressWarnings({\"rawtypes\""
},
{
"path": "code/chapter2_2_Mergesort/MergeBU.java",
"chars": 1850,
"preview": "package chapter2_2_Mergesort;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 自底向上的归并排序\n */\n@SuppressWarnings({\"rawtypes\""
},
{
"path": "code/chapter2_3_Quicksort/Ex25.java",
"chars": 2961,
"preview": "package chapter2_3_Quicksort;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\nimport chapter1_4_Analysis_of_Algorithms.Sto"
},
{
"path": "code/chapter2_3_Quicksort/Quick.java",
"chars": 1828,
"preview": "package chapter2_3_Quicksort;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\n/**\n * @author huang\n * 快速排序\n */\n@SuppressW"
},
{
"path": "code/chapter2_3_Quicksort/Quick3way.java",
"chars": 2149,
"preview": "package chapter2_3_Quicksort;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\n/**\n * @author huang\n * 三向切分的快速排序\n */\n@Supp"
},
{
"path": "code/chapter2_4_Priority_Queues/MaxPQ.java",
"chars": 1429,
"preview": "package chapter2_4_Priority_Queues;\n\n/**\n * 基于堆的优先队列\n * \n * @author huang\n */\npublic class MaxPQ<Key extends Comparable<"
},
{
"path": "code/chapter2_4_Priority_Queues/TopM.java",
"chars": 757,
"preview": "package chapter2_4_Priority_Queues;\n\nimport algs4.MinPQ;\nimport algs4.Stack;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\np"
},
{
"path": "code/chapter3_1_Symbol_Tables/BinarySearchST.java",
"chars": 3089,
"preview": "package chapter3_1_Symbol_Tables;\n\nimport algs4.Queue;\n\n@SuppressWarnings(\"unchecked\")\npublic class BinarySearchST<Key e"
},
{
"path": "code/chapter3_1_Symbol_Tables/FrequencyCounter.java",
"chars": 889,
"preview": "package chapter3_1_Symbol_Tables;\n\nimport algs4.ST;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * 符号表的用例\n * @author h"
},
{
"path": "code/chapter3_1_Symbol_Tables/SequentialSearchST.java",
"chars": 895,
"preview": "package chapter3_1_Symbol_Tables;\n\npublic class SequentialSearchST<Key, Value>{\n private Node first; // 链表首结点\n "
},
{
"path": "code/chapter3_2_Binary_Search_Trees/BST.java",
"chars": 5029,
"preview": "package chapter3_2_Binary_Search_Trees;\n\nimport algs4.Queue;\n\npublic class BST<Key extends Comparable<Key>, Value> {\n "
},
{
"path": "code/chapter3_4_Hash_Tables/LinearProbingHashST.java",
"chars": 2461,
"preview": "package chapter3_4_Hash_Tables;\n\nimport algs4.Queue;\n\n@SuppressWarnings(\"unchecked\")\npublic class LinearProbingHashST<Ke"
},
{
"path": "code/chapter3_4_Hash_Tables/SeparateChainingHashST.java",
"chars": 1220,
"preview": "package chapter3_4_Hash_Tables;\n\nimport java.util.Iterator;\n\nimport algs4.Queue;\nimport chapter3_1_Symbol_Tables.Sequent"
},
{
"path": "code/chapter3_5_Searching_Applications/SparseVector.java",
"chars": 717,
"preview": "package chapter3_5_Searching_Applications;\n\nimport chapter3_4_Hash_Tables.LinearProbingHashST;\n\n/**\n * @author huang\n * "
},
{
"path": "code/chapter3_5_Searching_Applications/WhiteFilter.java",
"chars": 578,
"preview": "package chapter3_5_Searching_Applications;\n\nimport java.util.HashSet;\n\nimport algs4.In;\nimport algs4.StdIn;\nimport algs4"
},
{
"path": "code/chapter4_1_Undirected_Graphs/BreadthFirstPaths.java",
"chars": 1269,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Queue;\nimport algs4.Stack;\n\npublic class BreadthFirstPaths {\n pri"
},
{
"path": "code/chapter4_1_Undirected_Graphs/CC.java",
"chars": 819,
"preview": "package chapter4_1_Undirected_Graphs;\n\n/**\n * 查找连通分量\n * @author huang\n */\npublic class CC {\n private boolean[] marked"
},
{
"path": "code/chapter4_1_Undirected_Graphs/Cycle.java",
"chars": 720,
"preview": "package chapter4_1_Undirected_Graphs;\n\n/**\n * 利用深度优先,判断 G 是否是无向图(假设不存在自环或平行边)\n * @author huang\n */\npublic class Cycle {\n"
},
{
"path": "code/chapter4_1_Undirected_Graphs/DegreesOfSeparation.java",
"chars": 1072,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * 间隔的度数\n * @author huang\n */\npubli"
},
{
"path": "code/chapter4_1_Undirected_Graphs/DepthFirstPaths.java",
"chars": 1053,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Stack;\n\n/**\n * edgeTo[w]=v 表示 v-w 是第一次访问 w 时经过的边\n * edgeTo[] 数组是一颗用父"
},
{
"path": "code/chapter4_1_Undirected_Graphs/DepthFirstSearch.java",
"chars": 546,
"preview": "package chapter4_1_Undirected_Graphs;\n\npublic class DepthFirstSearch {\n private boolean[] marked;\n private int cou"
},
{
"path": "code/chapter4_1_Undirected_Graphs/Graph.java",
"chars": 1041,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\n\npublic class Graph {\n private final int V;"
},
{
"path": "code/chapter4_1_Undirected_Graphs/SymbolGraph.java",
"chars": 1440,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.In;\nimport algs4.ST;\n\npublic class SymbolGraph {\n \n private ST"
},
{
"path": "code/chapter4_1_Undirected_Graphs/TestCC.java",
"chars": 822,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\nimport algs4.StdOut;\n\n/**\n * 找出一幅图的所有连通分量\n * @"
},
{
"path": "code/chapter4_1_Undirected_Graphs/TestPaths.java",
"chars": 699,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.In;\nimport algs4.StdOut;\n\n/**\n * 单点路径问题\n * @author huang\n */\npublic "
},
{
"path": "code/chapter4_1_Undirected_Graphs/TestSearch.java",
"chars": 555,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.In;\nimport algs4.StdOut;\n\npublic class TestSearch {\n\n public stat"
},
{
"path": "code/chapter4_1_Undirected_Graphs/TestSymbolGraph.java",
"chars": 548,
"preview": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class TestSymbolGraph {\n\n pub"
},
{
"path": "code/chapter4_1_Undirected_Graphs/TwoColor.java",
"chars": 783,
"preview": "package chapter4_1_Undirected_Graphs;\n\n/**\n * 判断 G 是否为二分图\n * @author huang\n */\npublic class TwoColor {\n private boole"
},
{
"path": "code/chapter4_2_Directed_Graphs/DepthFirstOrder.java",
"chars": 1052,
"preview": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Queue;\nimport algs4.Stack;\n\npublic class DepthFirstOrder {\n private"
},
{
"path": "code/chapter4_2_Directed_Graphs/Digraph.java",
"chars": 1346,
"preview": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\n\npublic class Digraph {\n \n private final i"
},
{
"path": "code/chapter4_2_Directed_Graphs/DirectedCycle.java",
"chars": 1228,
"preview": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Stack;\n\npublic class DirectedCycle {\n private boolean[] marked;\n "
},
{
"path": "code/chapter4_2_Directed_Graphs/DirectedDFS.java",
"chars": 1206,
"preview": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\nimport algs4.StdOut;\n\n/*\n * 深度优先搜索,解决单点可达性和多点可达性"
},
{
"path": "code/chapter4_2_Directed_Graphs/KosarajuSCC.java",
"chars": 930,
"preview": "package chapter4_2_Directed_Graphs;\n\n/*\n * 计算强连通分量的 Kosaraju 算法\n */\npublic class KosarajuSCC {\n private boolean[] mar"
},
{
"path": "code/chapter4_2_Directed_Graphs/SymbolDigraph.java",
"chars": 1464,
"preview": "package chapter4_2_Directed_Graphs;\n\nimport algs4.In;\nimport algs4.ST;\n\npublic class SymbolDigraph {\n \n private ST"
},
{
"path": "code/chapter4_2_Directed_Graphs/Topological.java",
"chars": 925,
"preview": "package chapter4_2_Directed_Graphs;\n\nimport algs4.StdOut;\n\n/*\n * 拓扑排序\n */\npublic class Topological {\n private Iterabl"
},
{
"path": "code/chapter4_2_Directed_Graphs/TransitiveClosure.java",
"chars": 381,
"preview": "package chapter4_2_Directed_Graphs;\n\n/*\n * 有向图顶点对可达性\n */\npublic class TransitiveClosure {\n private DirectedDFS[] all;"
},
{
"path": "code/chapter4_3_Minimum_Spanning_Tree/Edge.java",
"chars": 1039,
"preview": "package chapter4_3_Minimum_Spanning_Tree;\n\n/*\n * 带权重的边\n */\npublic class Edge implements Comparable<Edge> {\n private f"
},
{
"path": "code/chapter4_3_Minimum_Spanning_Tree/EdgeWeightedGraph.java",
"chars": 1501,
"preview": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.Bag;\nimport algs4.In;\n\n/*\n * 加权无向图\n */\npublic class EdgeWeighted"
},
{
"path": "code/chapter4_3_Minimum_Spanning_Tree/KruskalMST.java",
"chars": 821,
"preview": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.MinPQ;\nimport algs4.Queue;\n\npublic class KruskalMST {\n privat"
},
{
"path": "code/chapter4_3_Minimum_Spanning_Tree/LazyPrimMST.java",
"chars": 1270,
"preview": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport java.beans.Visibility;\n\nimport algs4.MinPQ;\nimport algs4.Queue;\n\n/*\n *"
},
{
"path": "code/chapter4_3_Minimum_Spanning_Tree/PrimMST.java",
"chars": 1467,
"preview": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.IndexMinPQ;\n\n/*\n * 最小生成树的 Prim(即时版本)\n */\npublic class PrimMST {\n"
},
{
"path": "code/chapter4_3_Minimum_Spanning_Tree/TestMST.java",
"chars": 431,
"preview": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.In;\nimport algs4.StdOut;\n\n/*\n * 最小生成树测试\n */\npublic class TestMST"
},
{
"path": "code/chapter4_3_Minimum_Spanning_Tree/UF.java",
"chars": 1888,
"preview": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class UF {\n private int[]"
},
{
"path": "code/chapter4_4_Shortest_Paths/DijkstraSP.java",
"chars": 1579,
"preview": "package chapter4_4_Shortest_Paths;\n\nimport algs4.IndexMinPQ;\nimport algs4.Stack;\n\n/**\n * @author huang\n * 最短路径的 Dijkstra"
},
{
"path": "code/chapter4_4_Shortest_Paths/DirectedEdge.java",
"chars": 625,
"preview": "package chapter4_4_Shortest_Paths;\n\n/**\n * @author huang\n * 加权有向边的数据类型\n */\npublic class DirectedEdge {\n private final"
},
{
"path": "code/chapter4_4_Shortest_Paths/EdgeWeightedDigraph.java",
"chars": 1300,
"preview": "package chapter4_4_Shortest_Paths;\n\nimport algs4.Bag;\nimport algs4.In;\n\n/**\n * @author huang\n * 加权有向图的数据类型\n */\npublic cl"
},
{
"path": "code/chapter4_4_Shortest_Paths/SP.java",
"chars": 289,
"preview": "package chapter4_4_Shortest_Paths;\n\n/**\n * @author huang\n * 最短路径的 API\n */\npublic interface SP {\n // 从顶点 s 到 v 的距离,如果不"
},
{
"path": "code/chapter4_4_Shortest_Paths/TestSP.java",
"chars": 667,
"preview": "package chapter4_4_Shortest_Paths;\n\nimport algs4.In;\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 最短路径测试\n */\npublic cla"
},
{
"path": "code/chapter5_3_Substring_Search/BoyerMoore.java",
"chars": 1559,
"preview": "package chapter5_3_Substring_Search;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * Boyer-Moore 字符串查找算法(启发式地处理不匹配地字符)\n *"
},
{
"path": "code/chapter5_3_Substring_Search/KMP.java",
"chars": 1329,
"preview": "package chapter5_3_Substring_Search;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * Knuth-Morris-Pratt 字符串查找算法\n */\npubli"
},
{
"path": "code/chapter5_3_Substring_Search/RabinKarp.java",
"chars": 2199,
"preview": "package chapter5_3_Substring_Search;\n\nimport java.math.BigInteger;\nimport java.util.Random;\n\nimport algs4.StdOut;\n\n/**\n "
},
{
"path": "code/chapter6_3_Suffix_Arrays/KWIC.java",
"chars": 894,
"preview": "package chapter6_3_Suffix_Arrays;\n\nimport algs4.In;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * @author huang\n * ke"
},
{
"path": "code/chapter6_3_Suffix_Arrays/LRS.java",
"chars": 541,
"preview": "package chapter6_3_Suffix_Arrays;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 最长重复子字符串算法的用例\n */\np"
},
{
"path": "code/chapter6_3_Suffix_Arrays/SuffixArray.java",
"chars": 1378,
"preview": "package chapter6_3_Suffix_Arrays;\n\nimport chapter2_3_Quicksort.Quick3way;\n\n/**\n * @author huang\n * 后缀数组(初级实现)\n */\npublic"
},
{
"path": "code/yuki.config.json",
"chars": 322,
"preview": "{\n \"title\": \"代码目录\",\n \"repository\": {\n \"index\": \"https://github.com/bighuang624/Algorithms-notes\",\n \"branch\": \"ma"
},
{
"path": "docs/.nojekyll",
"chars": 0,
"preview": ""
},
{
"path": "docs/Context/6.1_事件驱动模拟.md",
"chars": 163,
"preview": "# 6.1 事件驱动模拟\n\n\n\n### 性能\n\n对 N 个能够相互碰撞的粒子系统,**基于事件的模拟**在初始化时最多需要 N^2 次优先队列操作,在碰撞时最多需要 N 次优先队列操作(且对于每个无效的事件都需要一次额外的操作)。\n\n2.4"
},
{
"path": "docs/Context/6.2_B-树.md",
"chars": 107,
"preview": "# 6.2 B- 树\n\n作用:快速访问大量数据中的特定元素\n\n### 成本模型\n\n我们用**页**表示一块连续的数据,用**探查**表示访问一个页。因此外部查找算法的成本模型为**页的访问**次数(无论读写)。\n\n"
},
{
"path": "docs/Context/6.3_后缀数组.md",
"chars": 3791,
"preview": "# 6.3 后缀数组\n\n* 问题描述:在长度为数百万个字符的字符串中找出其**最长重复子字符串**。\n* 暴力解法:将字符串中每个起始位置为 i 的子字符串与另一个起始位置为 j 的子字符串相比较,记录匹配的最长子字符串。运行时间至少是字符"
},
{
"path": "docs/Context/6.4_网络流算法.md",
"chars": 1710,
"preview": "# 6.4 网络流算法\n\n### 定义\n\n* 一个**流量网络**是一张边的权重(这里称为**容量**)为正的加权有向图。\n* 一个 **st- 流量网络**有两个已知的顶点,即起点 s 和终点 t。\n* st- 流量网络中的 **st- "
},
{
"path": "docs/Context/6.5_问题规约.md",
"chars": 883,
"preview": "# 6.5 问题归约\n\n将很多看似复杂的问题归约为简单的问题,再用特定算法解决。\n\n但是注意不要犯下“Maslow 的锤子”的错误:沉迷于若干问题解决模型,从而妨碍发现更好的解决方法。\n\n### 排序问题\n\n以下问题可以被归约为排序问题:\n"
},
{
"path": "docs/Context/6.6_不可解性.md",
"chars": 1708,
"preview": "# 6.6 不可解性\n\n一台“图灵机”就是一台能够读取输入、变换状态和打印输出的有限状态机。它来自于两个重要的思想:\n\n* 普遍性:图灵机可以模拟所有物理可实现的计算设备。这被称为**丘奇-图灵论题**。\n* 可计算性:图灵机无法解决的问题"
},
{
"path": "docs/Fundamentals/1.3_背包、队列和栈.md",
"chars": 1860,
"preview": "# 1.3 背包、队列和栈\n\n## 可迭代的集合类型\n\nforeach 语句:\n\n```java\nQueue<Transaction> collection = new Queue<Transaction>();\n\nfor(Transact"
},
{
"path": "docs/Fundamentals/1.4_算法分析.md",
"chars": 1547,
"preview": "# 1.4 算法分析\n\n## 数学模型\n\n我们用`~f(N)`表示所有随着 N 的增大除以 f(N) 的结果趋近于 1 的函数,用`g(N)~f(N)`表示`g(N)/f(N)`随着 N 的增大趋近于 1。则 f(N) 为 g(N) 的增长"
},
{
"path": "docs/Fundamentals/1.5_案例研究:union-find算法.md",
"chars": 611,
"preview": "# 1.5 案例研究:union-find 算法\n\n## 动态连通性\n\n动态连通性问题:设计一个数据结构来保存程序已知的所有整数对的足够多的信息,并用它们来判断一对新对象是否是相连的。\n\n解决该问题的算法被称为 union-find。成本模"
},
{
"path": "docs/Graphs/4.1_无向图.md",
"chars": 2122,
"preview": "# 4.1 无向图\n\n## 术语表\n\n* 自环:一条连接一个顶点和其自身的边;\n* 平行边:连接同一对顶点的两条边;\n* 多重图:含有平行边的图;\n* 简单图:没有平行边或自环的图;\n* 子图:由一幅图的所有边的一个子集(以及它们所依附的所"
},
{
"path": "docs/Graphs/4.2_有向图.md",
"chars": 2574,
"preview": "# 4.2 有向图\n\n## 有向图中的可达性\n\n单点可达性:存在一条从顶点 s 到达顶点 v 的**有向路径**。\n\n### 标记-清除的垃圾收集\n\n标记-清除的垃圾回收策略会对每个对象保留一个位做垃圾收集之用。它会**周期性地运行一个类似"
},
{
"path": "docs/Graphs/4.3_最小生成树.md",
"chars": 2664,
"preview": "# 4.3 最小生成树\n\n本节研究最小生成树问题:给定一幅**加权无向图**,找到它的一棵最小生成树。\n\n## 术语表\n\n* 图的**生成树**:它的一棵含有其所有顶点的无环连通子图。\n* 一幅**加权图**的**最小生成树(MST)**:"
},
{
"path": "docs/Graphs/4.4_最短路径.md",
"chars": 1230,
"preview": "# 4.4 最短路径\n\n本节研究最短路径问题:找到从一个顶点到达另一个顶点的**成本最小**的路径。\n\n## 最短路径的性质\n\n### 需要解决的问题\n\n* 并不是所有顶点都是可达的:为了简化问题,约定图都是强连通的(每个顶点从另外任意一个"
},
{
"path": "docs/README.md",
"chars": 815,
"preview": "<h1 align=\"center\">《算法(第4版)》笔记</h1>\n\n<p align=\"center\"><a href=\"http://kyonhuang.top\"><img src=\"https://img.shields.io/b"
},
{
"path": "docs/Searching/3.1_符号表.md",
"chars": 1684,
"preview": "# 3.1 符号表\n\n**符号表**是一种存储键值对的数据结构,支持两种操作:\n\n* **插入(put)**,即将一组新的键值对存入表中;\n* **查找(get)**,即根据给定的键得到相应的值。\n\n## API\n\n符号表是一种典型的**抽"
},
{
"path": "docs/Searching/3.2_二叉查找树.md",
"chars": 1369,
"preview": "# 3.2 二叉查找树\n\n**定义**:一棵**二叉查找树(BST,或二叉搜索树)**是一棵二叉树,其中每个结点都含有一个 Comparable 的键(以及相关联的值)且每个结点的键都大于其左子树中的任意结点的键而小于右子树的任意结点的键。"
},
{
"path": "docs/Searching/3.3_平衡查找树.md",
"chars": 1162,
"preview": "# 3.3 平衡查找树\n\n前几种算法在最坏情况下的性能还是很糟糕。本节中介绍一种二分查找树并能保证无论如何构造它,它的运行时间都是对数级别的。\n\n理想情况下,我们希望能够保持二分查找树的平衡性,以使树高为 ~lgN,这样就能保证所有查找都能"
},
{
"path": "docs/Searching/3.4_散列表.md",
"chars": 3597,
"preview": "# 3.4 散列表\n\n使用散列的查找算法分为两步:\n\n1. 使用**散列函数**将被查找的键转化为数组的一个索引;\n2. **处理碰撞冲突**。\n\n两种解决碰撞的方法:**拉链法**和**线性探测法**。\n\n散列表是算法在**时间**和**"
},
{
"path": "docs/Searching/3.5_应用.md",
"chars": 1002,
"preview": "# 3.5 应用\n\n## 对符号表实现的选择\n\n| 算法(数据结构) | N 次插入后最坏情况下的查找成本 | N 次插入后最坏情况下的插入成本 | N 次随机插入后平均情况下的查找成本 | N 次随机插入后平均情况下的查找成本 | 是否高"
},
{
"path": "docs/Sorting/2.1_初级排序算法.md",
"chars": 3697,
"preview": "# 2.1 初级排序算法\n\n## 游戏规则\n\n### 排序算法类的模板\n\n```java\npublic class Example {\n public static void sort(Comparable[] a) {\n "
},
{
"path": "docs/Sorting/2.2_归并排序.md",
"chars": 997,
"preview": "# 2.2 归并排序\n\n**归并**:将两个有序的数组归并成一个更大的有序数组。\n\n归并排序能保证将任意长度为 N 的数组排序所需时间和 NlogN 成正比;但主要缺点是所需的额外空间和 N 成正比。\n\n每一次归并将涉及的所有元素复制到一个"
},
{
"path": "docs/Sorting/2.3_快速排序.md",
"chars": 1302,
"preview": "# 2.3 快速排序\n\n**特点:**\n\n* 原地排序(只需要一个很小的辅助栈);\n* 将长度为 N 的数组排序所需的时间和 NlgN 成正比。\n\n## 基本算法\n\n快速排序的**切分**方法:\n\n一般策略是先随意地选取 a[lo] 作为*"
},
{
"path": "docs/Sorting/2.4_优先队列.md",
"chars": 1458,
"preview": "# 2.4 优先队列\n\n优先队列最重要的操作就是**插入元素**和**删除最大元素**。\n\n**应用场景:**在某些数据处理的场合,**总数据量太大**(可以认为输入是无限的),无法排序(甚至无法全部装进内存)。如果将每个新的输入和已知的 "
},
{
"path": "docs/Sorting/2.5_应用.md",
"chars": 670,
"preview": "# 2.5 应用\n\n## 稳定性\n\n如果一个排序算法能够保留数组中**重复元素的相对位置**则可以被称为是**稳定**的。\n\n* 稳定的排序算法:插入排序、归并排序\n* 不稳定的排序算法:选择排序、希尔排序、快速排序和堆排序\n\n一般只有在稳"
},
{
"path": "docs/Strings/5.2_单词查找树.md",
"chars": 557,
"preview": "# 5.2 单词查找树\n\n* 查找命中所需的时间与被查找的键的长度成正比;\n* 查找未命中只需检查若干个字符。\n\n## 单词查找树\n\n单词查找树是由链接的结点所组成的数据结构,这些链接可能为空,也可能指向其他结点。每个结点都含有 R 条链接"
},
{
"path": "docs/Strings/5.3_子字符串查找.md",
"chars": 6439,
"preview": "# 5.3 子字符串查找\n\n* 问题描述:给定一段长度为 N 的文本和一个长度为 M 的**模式(pattern)**字符串,在文本中找到一个和该模式相符的子字符串。\n* 限制:模式相对文本较短(M 可能等于 100 或者 1000),而文"
},
{
"path": "docs/_sidebar.md",
"chars": 1041,
"preview": "- **第 1 章 基础**\n - 1.1 基础编程模型\n - 1.2 数据抽象\n - [1.3 背包、队列和栈](Fundamentals/1.3_背包、队列和栈)\n - [1.4 算法分析](Fundamentals/1.4_算"
},
{
"path": "docs/index.html",
"chars": 1000,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>《算法(第4版)》笔记</title>\n <meta http-equiv=\"X-UA-C"
},
{
"path": "package.json",
"chars": 646,
"preview": "{\n \"name\": \"Algorithms-notes\",\n \"version\": \"1.0.0\",\n \"description\": \"《算法(第4版)》笔记\",\n \"main\": \"index.js\",\n \"scripts\":"
},
{
"path": "每一节可以再看一遍的题.md",
"chars": 66,
"preview": "## 每一节可以再看一遍的题\n\n### 1.1\n\n1.1.9 将一个正整数 N 用二进制表示并转换为一个 String 类型的 s\n"
},
{
"path": "相关问题解决方法.md",
"chars": 162,
"preview": "## Eclipse命令行参数使用\n\nRun---->Run Configurations----->右边 Arguments 里 Program arguments 中写。\n\n如果写的是文件,默认该文件要放在项目的根目录里。当然也可以换位"
}
]
About this extraction
This page contains the full source code of the bighuang624/Algorithms-notes GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 169 files (543.9 KB), approximately 160.8k tokens, and a symbol index with 1084 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.