第一章 基础
算法
算法 是一种 有限的,确定的,有效的,并适合用计算机程序来实现的解决问题的方法。
数据结构 是算法的副产品 或者 结果。
算法分析 是 为一项任务选择最合适的算法的过程。
1.1 基础编程模型
基础编程模型 : 把描述和实现算法所用到的语言特性,软件库和操作系统特性总称为 基础编程模型。
1.1.10 二分查找
代码功能:白名单过滤 ,根据输入的数字判断该数字是否在已知的数组中,如果不存在则打印在控制台
import java.util.Arrays; import edu.princeton.cs.algs4.*; public class BinarySearch { public static int rank(int key, int[] a) { int lo = 0; int hi = a.length - 1; while (lo <= hi) { 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; } public static void main(String[] args) { int[] whileList = In.readInts(args[0]); Arrays.sort(whileList); while (!StdIn.isEmpty()) { int key = StdIn.readInt(); if (rank(key, whileList) == -1) { StdOut.println(key); } } } }命令行运行:
javac -classpath algs4.jar; BinarySearch.java java -classpath algs4.jar; BinarySearch algs4-data\largeT.txt