1. 程式人生 > >漸進性分析(asymptomatic analysis)& 大O的數學定義&時間複雜度

漸進性分析(asymptomatic analysis)& 大O的數學定義&時間複雜度

一、什麼是漸進性分析?

 

假設同一個任務,有2種演算法, 如何去找出那個更好?

一個簡單的辦法——用兩個程式實現這兩種演算法,然後輸入不同的資料,在你電腦上執行這兩個程式,看看那個需要的時間更少。 用這種方法分析演算法,有很多問題。

1. 對一些輸入,可能第一個效能更好;對另外一些,可能第二更好

2. 對一些輸入,第一個演算法在一臺機器上表現更好,另外一個演算法在其它的機器上更好。

 

漸進性分析是為解決上面演算法分析中的問題。根據輸入規模來評估一個演算法的效能,而不是測量實際執行時間。

通過輸入規模的增加來計算演算法需要的時間和空間的增長趨勢。

 

參考: Analysis of Algorithms

Given two algorithms for a task, how do we find out which one is better?
One naive way of doing this is – implement both the algorithms and run the two programs on your computer for different inputs and see which one takes less time. There are many problems with this approach for analysis of algorithms.
1) It might be possible that for some inputs, first algorithm performs better than the second. And for some inputs second performs better.
2) It might also be possible that for some inputs, first algorithm perform better on one machine and the second works better on other machine for some other inputs

 

Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don’t measure the actual running time). We calculate, how does the time (or space) taken by an algorithm increases with the input size.

 

二、大O的數學定義

 

 大O符號(Big O notation)是用於描述函式漸進行為的數學符號。

 它用另一個(通常更簡單的)函式來描述一個函式數量級的漸近上界。

 

 準確的數學定義:

  若T(n)和f(n)是定義在正整數集合上的兩個函式,則存在正的常數C和n0,使得當n≥n0時,滿足  0≤T(n)≤C*f(n)

  記為:      T(n)=O(f(n))

  也就是當n→∞時,f(n)的函式值增長速度與T(n)的增長速度同階。

 

 

三、時間複雜度

 

 時間複雜度描述了該演算法的執行時間,可以通過演算法中的基本操作的執行次數來度量,記作  T(n)。它是問題規模n的函式。

   T(n)=O(f(n)),   n→∞時,f(n)的函式值增長速度與T(n)的增長速度同階

 可以用更簡單的f(n)來分析演算法的時間複雜度。即  O(f(n) 來表示其演算法複雜度。

 時間複雜度不僅依賴於問題的規模n,也取決於待輸入資料的性質(如資料的初始狀態,對輸入資料已經有序,不同排序演算法時間複雜度不一樣)。