本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论
知识点
- 引用
- 别名
- 非主流 二分法查找的实现
题目
1.2.8设 a[] 和 b[] 均为长数百万的整型数组。以下代码的作用是什么?有效吗?
int[] t = a; a = b; b = t;
1.2.8 Suppose that a[] and b[] are each integer arrays consisting of millions of integers. What does the follow code do? Is it reasonably efficient?
int[] t = a; a = b; b = t;
Answer. It swaps them. It could hardly be more efficient because it does so by copying references, so that it is not necessary to copy millions of elements.
答案
作用就是交换两个数组。
在JAVA 中,数组变量实际是数组的一个引用(类似于指针),交换两个引用的效率与数组大小无关,都是常数时间的。
题目
1.2.9 修改 BinarySearch(请见 1.1.10.1 节中的二分查找代码),使用 Counter 统计在有查找中被检查的键的总数并在查找全部结束后打印该值。
提示:在 main() 中创建一个 Counter 对象并将它作为参数传递给 rank()
1.2.9 Instrument BinarySearch(page47) to use a Counter to count the total number of keys examined during all searches and then print the total after all searches are com- plete. Hint : Create a Counter in main() and pass it as an argument to rank().
答案
Counter.java
public class Counter {
public int counter;
}
BinarySearchCounter.java
public class BinarySearchCounter {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] numArray = { 1, 2, 3, 4, 67, 88, 89, 101, 222, 788, 999 };
Counter counter = new Counter();
int index = rank(222, numArray, counter);
System.out.println("index: " + index + "\ncouter:" + counter.counter);
}
public static int rank(int t, int[] array, Counter counter) {
int lo = 0;
int hi = array.length - 1;
int mid = (lo + hi) / 2;
while (t != array[mid]) {
counter.counter++;
if (t < array[mid]) {
if (hi == mid) {
return -1;
}
hi = mid;
} else if (t > array[mid]) {
if (lo == mid) {
return -1;
}
lo = mid;
} else {
return mid;
}
mid = (lo + hi) / 2;
}
return mid;
}
}
代码索引
视频讲解
广告
我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。
本人所有简书的算法文章已经移入小专栏:算法四习题详解