2015-06-14 70 views
-2

以下代碼的大表示法是什麼?我仍然無法完全理解這個概念。 我應該從經驗豐富的編碼人員那裏得到一個基於此代碼的大o性能摘要。Java堆棧數組 - 大O表示法

import java.util.*; 
import java.util.InputMismatchException; 
import javax.swing.*; 
public class MyStack { 

    private int maxSize; 
    private long[] stackArray; 
    private int top; 
    public MyStack(int s) { 
     maxSize = s; 
     stackArray = new long[maxSize]; 
     top = -1; 
    } 
    public void push(long j) { 
     stackArray[++top] = j; 
     System.out.println("Push onto stack"); 
    } 
    public long pop() { 
     return stackArray[top--]; 
    } 
    public long peek() { 
     return stackArray[top]; 
    } 
    public boolean isEmpty() { 
     return (top == -1); 
    } 
    public boolean isFull() { 
     return (top == maxSize - 1); 
    } 
    public static void main(String[] args) { 
     Scanner num = new Scanner(System.in); 
     int input =0; 
     int x; 
     MyStack theStack = new MyStack(5); 
    for(x=0; x<5; x++) 
    { 


     System.out.println("\nEnter a number(Push): "); 
     input = num.nextInt(); 
     theStack.push(input); 



     } 



    System.out.print("The first element on the top is the top of the stack"); 
    System.out.println(""); 
     while (!theStack.isEmpty()) { 
     long value = theStack.pop(); 
     System.out.print(value); 
     System.out.println(" Pop"); 

     } 


     System.out.println(""); 

    } 
} 
+0

一個班級沒有大O的複雜性。你的問題是什麼? – 2015-06-15 07:00:45

回答

0

大O性能因您嘗試的操作而異。看看你的「isEmpty()」方法。它總是隻看頂部的值,所以這是常數,或O(1)。我沒有看到你的類中的其他方法(除main(),我們將在一分鐘內看到),它們依賴於數組中的元素數量,它們都只與top一起工作。

main()只是要求5個值,然後打印出來。如果它要求50,則需要延長十倍(假設用戶輸入保持相對恆定)。所以main是O(n),其中n是數組中元素的數量。

如果你正在尋找的陣列在一個特定的號碼,你很可能要檢查每一個反過來,所以O(N)。

如果您在查看每個元素後做了一些更復雜的操作,然後做了一些操作或與其他元素進行比較(例如,使用嵌套for循環),您最終會得到O(n^2)。

希望能幫助你的思考過程。

0

的所有方法的性能是在O(1),因爲它們僅僅索引陣列或檢查對頂部的值。

在主for循環被執行5次體,進行5所推動,從而O(5×1)= O(N),因爲堆疊具有大小爲n = 5。

之後while循環將彈出堆棧直到它爲空。因爲堆棧只能包含5個元素(這也是它的大小),這又是O(5 * 1)= O(n)。

所以,你可以認爲它是在O(2 * N)的產生爲O(n)。的操作的

0

數據結構複雜總是針對其持有,是元件的數目來計算表示將採取與增加元件的數目最大時間。

enter image description here

例如:它會需要花多少時間來搜索元素中的「B樹」鑑於存在已經在它的元素的n個。

enter image description here

在B樹搜索時間爲O(log n)的,意味着最大搜索時間將成長爲日誌n的函數(見大O複雜性曲線圖)。你的操作並不依賴於棧中攜帶的元素,因爲在特定位置獲取元素的複雜度是O( 1)。因此,所有的操作需要O(1)時間。

推 - O(1)

流行 - O(1)

isFull - O(1)

的isEmpty - O(1)

但是,如果你執行搜索你的堆棧中,檢查給定的long是否在你的堆棧中,然後搜索取決於你必須遍歷所有元素的元素,複雜度將是O(n)。