算法4是一本非常好的书,加上快要毕业面试了,用这个重新复习一下,还可以看看他给的stdlib类库的源码,学习下java标准库的封装。
准备1
书中使用了 < 重定向,无奈eclipse控制台不支持这玩意儿,只能用java的setIn方法了。这是第一个准备工作,重定向文件输入流,不过需要捕获异常,比原来的代码要丑了,暂时没想到好方法。
package com.duoduo.algs4.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class RedirectStream {
private static FileInputStream fis = null;
public static FileInputStream redirectFileToStdin(String path) throws FileNotFoundException{
fis = new FileInputStream(path);
System.setIn(fis);
return fis;
}
}
准备2
这本书最吸引我的地方在于它封装了画图的玩意儿,解决了我长久以来的疑惑,因为以前经常会看见有人在写算法的时候搞一些图片在展示排序的数组或者随机的点儿云云,现在知道怎么弄了,很开心。一下为测试类,并没有使用泛型,只写了int,double型的数组。
package com.duoduo.std;
import java.util.Arrays;
import org.junit.Test;
import com.duoduo.algs4.util.Util;
import edu.princeton.cs.introcs.Draw;
import edu.princeton.cs.introcs.StdRandom;
public class DrawArray {
public static Draw DrawLine(){
int N = 100;
Draw draw = new Draw("画线");
draw.setXscale(0,N);
draw.setYscale(0,N*N);
draw.setPenRadius(.01);
for(int i = 0; i < N; i++){
draw.point(i, i);
draw.point(i, i*i);
draw.point(i, i*Math.log(i) );
}
return draw;
}
public static Draw DrawArray(int[] a,String name){
double[] b = Util.copy(a);
return DrawArray(b,name);
}
public static Draw DrawArray(double[] a,String name){
Draw draw = new Draw(name);
return DrawArray(a,0.5,2.0,draw);
}
public static Draw DrawArray(int[] a,double X_DOWN,double Y_DOWN,String name){
Draw draw = new Draw(name);
return DrawArray(a,X_DOWN,Y_DOWN,draw);
}
public static Draw DrawArray(int[] a,double X_DOWN,double Y_DOWN,Draw draw){
double[] b = Util.copy(a);
return DrawArray(b,X_DOWN,Y_DOWN,draw);
}
public static Draw DrawArray(double[] a,double X_DOWN,double Y_DOWN,String name){
Draw draw = new Draw(name);
return DrawArray(a,X_DOWN,Y_DOWN,draw);
}
public static Draw DrawArray(double[] a,double X_DOWN,double Y_DOWN,Draw draw){
//建议Y_DOWN为最大数值的两倍
int N = a.length;
for(int i = 0; i < N; i++){
double x = 1.0 * i / N;
double y = a[i] / Y_DOWN;
double rw = X_DOWN/N;
double rh = a[i] / Y_DOWN;
draw.filledRectangle(x, y, rw, rh);
}
return draw;
}
public static Draw DrawRandomArray(){
int N = 50;
double[] a = new double[N];
for(int i = 0; i < N; i++){
a[i] = StdRandom.random();
}
return DrawArray(a,"随机数组");
}
public static Draw DrawSortedArray(){
int N = 50;
double[] a = new double[N];
for(int i = 0; i < N; i++){
a[i] = StdRandom.random();
}
Arrays.sort(a);
return DrawArray(a,"排序数组");
}
public static Draw DrawSortedArray2(){
int N = 50;
int[] a = new int[N];
for(int i = 0; i < N; i++){
a[i] = i;
}
Arrays.sort(a);
return DrawArray(a,0.5,N*2,"设定高度的排序数组");
}
public static void main(String[] args) {
DrawLine();
DrawRandomArray();
DrawSortedArray();
DrawSortedArray2();
}
}
![](http://static.oschina.net/uploads/space/2013/0704/090233_WfUT_585840.png)
准备工作结束。