2015-09-04 32 views
0

這是我的計劃,我能夠得到的時間複雜度部分任何人都可以幫我這個:存儲數組元素的時間複雜度

我'能得到他們中的一些,但任何人都可以驗證,如果我方法正確

package sd; 

public class Max { 

    public static void main(String args[]) { 
     int i; 
     int large[] = new int[5]; 
     int array[] = { 33, 55, 13, 46, 87, 42, 10, 34, 43, 56 }; 
     int max = 0, index = 0; 

     // O(5) 
     for (int j = 0; j < 5; j++) { 

      max = array[0]; // Assuming max to be first element 

      // Comparing 1st element with max O(n) 
      for (i = 1; i < array.length; i++) { 
       if (max < array[i]) { 
        max = array[i]; // Replace if greater 
        index = i; 
       } 
      } 
      large[j] = max; 
      array[index] = Integer.MIN_VALUE; // Find max and replace with least 
               // possible value to avoid 
               // duplicate max 

      System.out.println("Largest 5 amoung 10 : " + large[j]); // Time 
                     // complexity: 
                     // O(5) 
                     // * 
                     // O(n) 
                     // = 
                     // O(n) 
     } 
    } 

} 
+0

也許你應該指定你的代碼的哪些參數是常量,哪些不是。否則你的代碼似乎不會接收任何輸入數據,所以它完全獨立於輸入大小,所以它可能運行在'O(1)':-) – vojta

回答

0

這裏的複雜性是O(5N)

有關查找複雜性檢查this question的更多信息,

+0

它嵌套for循環,我假設它有O(n2 ) –

+0

如果兩個循環的大小是相同的,那麼'N * N = N^2'但是第一個循環是固定的,所以'5 * N' –

+0

不能忽略這些常量嗎? –