2013-03-13 118 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)); 

你的代码保持添加元素,而不是移动它们。