1. 程式人生 > >612.1.002 ALGS4 | Analysis of Algorithms

612.1.002 ALGS4 | Analysis of Algorithms

app and int all head pwa per new out

我們生活在大數的時代
培養數量級的敏感!
Tip:見招拆招

  • 作為工程師,你先要能實現出來。
  • 充實基礎,沒有什麽不好意思
  • 哪怕不完美。但是有時候完成比完美更重要。
  • 之後再去想優化

P.S.作者Robert Sedgewick的導師是Knuth(高德納!)

Conclusion First

1.Running Time

技術分享圖片

  • Operation table

技術分享圖片

2.Memory

1 SOP - Analysis

技術分享圖片

2 Observations

  • Measuring the running time - automatic

public class Stopwatch(part of stdlib.jar/algs4.course)


    public static void main(String[] args) {
        In in = new In(args[0]);
        int[] a = in.readAllInts();

        Stopwatch timer = new Stopwatch();
        int count = count(a);
        StdOut.println("elapsed time = " + timer.elapsedTime());//time since creation (in seconds)
        StdOut.println(count);
    }


3 Mathematical Model - Knuth(高德納!)

Simplification 1: cost model

技術分享圖片

Simplification 2: tilde notation

approximate

工程近似

技術分享圖片

技術分享圖片

  • Bottom line. Use cost model and tilde notation to simplify counts.

4 Order of growth

技術分享圖片

  • Operation table

技術分享圖片

5 Binary Search - code 二分搜索

不看代碼自己寫
技術分享圖片

public static int binarySearch(int[]a,int key)
        {
        int lo=0;
        int hi=a.length-1;
        while(lo<=hi){
            int mid=lo+(hi-lo)/2;
            if(key>a[mid])lo=mid+1;
            else if(key<a[mid])hi=mid-1;
            else return mid;
        }
        return-1;
        }

6 Memory

技術分享圖片

Typical memory usage of Java

Object overhead - 對象開銷
技術分享圖片

QuickUnion

技術分享圖片

612.1.002 ALGS4 | Analysis of Algorithms