今天开始学算法和java系列emmmm
本人用的是mac,根据https://algs4.cs.princeton.edu/mac/步骤一步步搭建环境即可。(自带网站上面有很多资料,看不懂英语的话...学英语吧)
用Drjava编译本书第一个例子,二分查找算法。(虽然本来准备用idea编译)
源代码网站上有,下载 algs4.jar 和 algs4-data.zip 。解压zip的文件和jar和Java程序什么的放在同个地方就好。
新建工程时注意将jar导入,然后程序中加入import edu.princeton.cs.algs4.*;即可使用书本提到的库。
/******************************************************************************
* Compilation: javac BinarySearch.java
* Execution: java BinarySearch whitelist.txt < input.txt
* Dependencies: In.java StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/11model/tinyW.txt
* https://algs4.cs.princeton.edu/11model/tinyT.txt
* https://algs4.cs.princeton.edu/11model/largeW.txt
* https://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]
*
******************************************************************************/
import edu.princeton.cs.algs4.*;
import java.util.Arrays;
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);
}
}
}
如果在交互台运行则会出现这样的情况,百度了一下大约是重定向的原因,目前我了解的就是这样的重定向只能在终端里运行,待以后更了解重定向了估计会明白为什么