算法練習(22):Java基礎:引用,別名,二分法查找(1.2.8-1.2.9)

本系列博客習題來自《算法(第四版)》,算是本人的讀書筆記,如果有人在讀這本書的,歡迎大家多多交流。為了方便討論,本人新建了一個微信群(算法交流),想要加入的,請?zhí)砑游业奈⑿盘枺簔hujinhui207407 謝謝。另外,本人的個人博客 http://www.kyson.cn 也在不停的更新中,歡迎一起討論

算法(第4版)

知識點

  • 引用
  • 別名
  • 非主流 二分法查找的實現(xiàn)

題目

1.2.8設 a[] 和 b[] 均為長數(shù)百萬的整型數(shù)組。以下代碼的作用是什么?有效嗎?
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.

答案

作用就是交換兩個數(shù)組。
在JAVA 中,數(shù)組變量實際是數(shù)組的一個引用(類似于指針),交換兩個引用的效率與數(shù)組大小無關,都是常數(shù)時間的。

題目

1.2.9 修改 BinarySearch(請見 1.1.10.1 節(jié)中的二分查找代碼),使用 Counter 統(tǒng)計在有查找中被檢查的鍵的總數(shù)并在查找全部結(jié)束后打印該值。
提示:在 main() 中創(chuàng)建一個 Counter 對象并將它作為參數(shù)傳遞給 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;
    }

}

代碼索引

BinarySearchCounter.java

視頻講解

點此觀看分析視頻

廣告

我的首款個人開發(fā)的APP壁紙寶貝上線了,歡迎大家下載。

本人所有簡書的算法文章已經(jīng)移入小專欄:算法四習題詳解

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容