链表插入

时间:2013-03-13 01:53:49

标签: java heap insertion-sort

当我尝试在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);
    }
}

1 个答案:

答案 0 :(得分:1)

这似乎可以修复你的方法:

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

您的代码不断添加元素而不是移动元素。