美文网首页算法第四版习题讲解
算法练习(4):二分法查找(1.1.22-1.1.25)

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

作者: kyson老师 | 来源:发表于2017-08-21 11:06 被阅读983次

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

算法(第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壁纸宝贝上线了,欢迎大家下载。

相关文章

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

    本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本...

  • 查找算法

    三种查找算法:顺序查找,二分法查找(折半查找),分块查找,散列表

  • 刷前端面经笔记(九)

    1.JavaScript实现二分法查找? 二分法查找,也称折半查找,是一种在有序数组中查找特定元素的搜索算法。查找...

  • 算法图解1-2/11

    原书作者 Aditya Bhargava 1 算法简介 1.1 二分法查找 二分法查找,正是猜数字游戏的玩法:A...

  • 查找算法

    查找算法 顺序查找法 时间复杂度:O(n) 二分法查找 二分法查找适用于有顺序的序列 时间复杂度:O(n) 核心思...

  • 前端面试之算法二分法

    使用二分法的前提是,目标数组的元素必须是有序排列的,所以二分法属于有序查找算法 二分法又称为“折半查找”,从数组的...

  • 二分法查找

    二分法查找 : 目的 : 查找一个数组中是否含义某个元素 : 有返回数组中的位置 ,没有返回 -1 算法: 二分法...

  • 解析前端面试之二分查找算法

    二分法查找,也称为折半法,是一种在有序数组中查找特定元素的搜索算法。 二分法查找的思路如下: (1)首先,从数组的...

  • 算法:二分法查找(折半查找法)

    算法:二分法查找(折半查找法) 这是最经典的折半查找,而在面试的时候往往会对某些经典的数据结构和算法进行魔改,这道...

  • 二分法查找

    二分法查找 算法:二分法查找适用于数据量较大,但是数据需要先排好序 (1)确定该区间的中间位置k(2)将查找的值T...

网友评论

  • xiehou31415926:你好,我刚学算法,最近在你这里收获了不少,对1.1.23有疑问,添加一个参数:+ 打印出标准输入中不在白名单上的值; -则打印出标准输入中在名单上的值,这句话应该没在程序里表述正确,是参数不是打印的标记吧,不知道理解错没
    smallbabyting:1.1.24中rem=M%N;要当N不为0时才能除吧
    kyson老师:改好了,谢谢你提出啊
    kyson老师:好的,我看一下,再给你回复

本文标题:算法练习(4):二分法查找(1.1.22-1.1.25)

本文链接:https://www.haomeiwen.com/subject/krdcdxtx.html