2013-03-13 115 views
0

任何人都可以告訴我爲什麼Iam在我嘗試在2000個元素的列表上運行此代碼時運行堆空間?鏈接列表插入

public static <T extends Comparable <? super T>> void insertionSort2(List<T> portion){ 
    int i = 0; 
    int j = 0; 
    T value; 
    //List <T> sorted = new LinkedList<T>(); 

    // goes through the list 
    for (i = 1; i < portion.size(); i++) { 

     // takes each value of the list 
     value = (T) portion.remove(i); 

     // the index j takes the value of I and checks the rest of the array 
     // from the point i 
     j = i - 1; 

     while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) { 
      portion.add(j + 1, portion.get(j)); 

      j--; 

     } 
     // put the value in the correct location. 
     portion.add(j + 1, value); 
    } 
} 
+0

如果您檢查格式並告訴我們您正在使用哪種編程語言,它可能會有所幫助。 – redtuna 2013-03-13 01:59:36

+0

它看起來像part.add可能被稱爲二次數 - 也許列表只是增長太大? – redtuna 2013-03-13 02:01:18

+0

我正在使用java。有一點上下文:我想要爲列表接口的插入排序提供一個實現,這將有利於linkedlist over arraylist。因此,我試圖使用添加和刪除方法,而不是get和set。 – gadona91 2013-03-13 03:27:40

回答

1

這似乎解決您的方法:

while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) { 
      portion.add(j, portion.remove(j)); 

你的代碼保持添加元素,而不是移動它們。