算法练习(4):二分法查找(1.1.22-1.1.25)

本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论

《算法练习(4):二分法查找(1.1.22-1.1.25)》 算法(第4版)

知识点

  • 二分法查找(BinarySearch)
  • 欧几里得算法

题目

1.1.22 使用1.1.6.4 中的 rank()递归方法重新实现 BinarySearch 并跟踪该方法的调用。每当该方法被调用时,打印出它的参数 lo 和 hi 并按照递归的深度缩进。提示 :为递归方法加一个参数来保存递归的深度。

1.1.22 Write a version of Binary Search that uses the recursive rank() given on page 25 and traces the method calls. Each time the recursive method is called, print the argument values lo and hi, indented by the depth of the recursion. Hint: Add an argument to the recursive method that keeps track of the depth.

分析

书中的1.1.6.4介绍的二分法的递归实现如下:

public static int rank(int key, int[] a) {  
    return rank(key, a, 0, a.length - 1);  
}
public static int rank(int key, int[] a, int lo, int hi) { 
    //如果key存在于a[]中,它的索引不会小于lo且不会大于hi
    if (lo > hi) 
        return -1;
    int mid = lo + (hi - lo) / 2;
    if(key < a[mid])
        return rank(key, a, lo, mid - 1);
    else if (key > a[mid])
        return rank(key, a, mid + 1, hi);
    else                   
        return mid;
}

答案

public static int rank (int key,int[] a) {
    return rank(key,a,0,16,1);
}
public static int rank (int key,int[] a,int lo,int hi,int deep) {
    if (hi < lo) return - 1;
    int mid = lo + (hi - lo) / 2;
    for(int i = 0 ; i < deep ; i++)
        System.out.print(" ");
    System.out.println("lo: "+lo+" hi: "+hi);
    if (key < a[mid])
        return rank (key,a,lo,mid - 1,deep + 1);
    else if (key > a[mid])
        return rank (key,a,mid + 1,hi,deep + 1);
    else
        return mid;
}   

测试用例

public static void main(String[] args) {
    int[] array = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    rank(10,array);
}
/**打印出的结果
  lo: 0  hi: 16
    lo: 9  hi: 16
      lo: 9  hi: 11
**/

代码索引

BinarySearchRecursion.java

题目

1.1.23 为 BinarySearch 的测试用例添加一个参数:+ 打印出标准输入中不在白名单上的值; -,则打印出标准输入中在名单上的值。

1.1.23 Add to the BinarySearch test client the ability to respond to a second argument: + to print numbers from standard input that are not in the whitelist, – to print numbers that are in the whitelist.

分析

解答这道题需要我们对IDE环境(这里使用eclipse)做一些设置,我也写了一篇教程:算法练习(5):Eclipse简易教程
感谢@xiehou31415926提出。之前这题我理解错误,现在给读者解释一下这道题的意思,“+”和“-”是作为参数传进来的。当传入的参数是“+”时则打印出标准输入中不在白名单上的值。

答案

public class BinarySearchWithParams {
    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) {
        //这里参数symbol本来是要传进来的,这里写死,是为了Demo方便
        char symbol = '-';
        int[] whitelist = {1,2,3,4,5,6,7,11,222};
        Arrays.sort(whitelist);
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            int found = rank(key, whitelist);
            if ('+' == symbol && found == -1)
                StdOut.println(key);
            if ('-' == symbol && found != -1)
                StdOut.println(key);
        }
    }
}

代码索引

BinarySearchWithParams.java

题目

1.1.24 给出使用欧几里得算法计算 105 和 24 的最大公约数的过程中得到的一系列 p 和 q 的值。扩展该算法中的代码得到一个程序Euclid,从命令行接受两个参数,计算它们的最大公约数并打印出每次调用递归方法时的两个参数。使用你的程序计算 1 111 111 和 1 234 567 的最大公约数。

1.1.24 Give the sequence of values of p and q that are computed when Euclid’s algo- rithm is used to compute the greatest common divisor of 105 and 24. Extend the code given on page 4 to develop a program Euclid that takes two integers from the command line and computes their greatest common divisor, printing out the two arguments for each call on the recursive method. Use your program to compute the greatest common divisor or 1111111 and 1234567.

分析

最大公约数(greatest common divisor,缩写为gcd)指两个或多个整数共有约数中最大的一个。a,b的最大公约数记为(a,b),同样的,a,b,c的最大公约数记为(a,b,c),多整数的最大公约数也有同样的记号。
欧几里德算法又称辗转相除法,是指用于计算两个正整数a,b的最大公约数。计算公式gcd(a,b) = gcd(b,a mod b)。

答案

    public static int gcd(int m,int n) {
        int rem = 0;
        int M = m;
        int N = n;
        if (m < n) {
            M = n ;
            N = m ;
        }
        rem = M % N ;
        if (0 == rem)
            return N;
        System.out.println("m:"+ N + ";n:" + rem);
        return gcd(N, rem);
    }

    public static void main (String[] args) {
        
        int a =gcd(1111111 ,  1234567);
        System.out.println(a + "");

    }

/**
 输出如下:

m:1111111;n:123456
m:123456;n:7
m:7;n:4
m:4;n:3
m:3;n:1
1

**/

题目

1.1.25 使用数学归纳法证明欧几里得算法能够计算任意一对非整数p和q的最大公约数。

1.1.25 Use mathematical induction to prove that Euclid’s algorithm computes the greatest common divisor of any pair of nonnegative integers p and q.

广告

我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。

    原文作者:kyson老师
    原文地址: https://www.jianshu.com/p/061b1d5613ee#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞