Algs4-1.2.9使用Counter统计BinarySearch检查的key个数

本文介绍了一种改进的二分查找算法实现,通过引入计数器统计查找过程中被检查键的总数,增强算法的监控与分析能力。文章提供了完整的Java代码示例,包括BinarySearch类和Counter类的定义,展示了如何在主函数中创建并利用Counter对象来跟踪二分查找过程中的键检查次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.2.9修改BinarySearch(请见1.1.10.1节中的二分查找代码),使用Counter统计在有查找中被检查的键的总数并在查找全部结束后打印该值。提示:在main()中创建一个Counter对象并将它作为参数传递给rank()。
答:
图片
BinarySearch Code:
import java.util.Arrays;

public class Test
{
  public static void main(String[] args) 
  {
    int[] whitelist=In.readInts(args[0]);
    Arrays.sort(whitelist);
    Counter counterKey=new Counter("counterKey");
    while (!StdIn.isEmpty())
    {
        int key=StdIn.readInt();
        int indexOfWhite=rank(key,whitelist,counterKey);
    }
     StdOut.printf("BinarySearch check Key Counter is:%d\n",counterKey.tally());
    }//end main
 
  public static int rank(int key,int[] a,Counter counterKey)
  {
      int lo=0;
      int hi=a.length-1;
      while(lo<=hi)
      {
          counterKey.increment();
          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;
  }
}//end class Test


////////////////////////////////////
Counter Code:
public class Counter
{
    private final String name;
    private int count;
    public Counter(String id)
    {
        name=id;
        count=0;
    }  
   
    public void increment()
    {
        count++;
    }
   
    public int tally()
    {
        return count;
    }
   
    public String ToString()
    {
        return count+ " " +name;
    }
   
    public static void main(String[] args)
    {
        Counter heads=new Counter("heads");
        Counter tails=new Counter("tails");
       
        heads.increment();
        heads.increment();
        tails.increment();
       
        StdOut.println(heads+" " + tails);
        StdOut.println(heads.tally() + tails.tally());
       
    }
}

转载于:https://www.cnblogs.com/longjin2018/p/9848850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值