×

# 算法练习(22):Java基础：引用，别名，二分法查找(1.2.8-1.2.9)

• 引用
• 别名
• 非主流 二分法查找的实现

## 题目

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.

## 题目

1.2.9 修改 BinarySearch（请见 1.1.10.1 节中的二分查找代码），使用 Counter 统计在有查找中被检查的键的总数并在查找全部结束后打印该值。

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;
}

}
``````

### 代码索引

BinarySearchCounter.java