linkedList insertionsort



这是我使用linkedList的插入排序方法的实现。我已经尝试过了,它工作得很好,唯一的问题是有一个索引越界异常引起的J+1行。谁能告诉我如何解决这个问题或如何解决它?非常感谢

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.remove(j));//it was j+1
            j--; 

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

查看这段代码

把它作为一个函数放在一个类中,然后试着调用它

void InsertionSort()
{
    int temp, out, in;
    for(out=1 ; out<size ; out++)
    {
        temp = list[out];
        in = out;
        while (in > 0 && list[in-1] > temp)
        {
            list[in] = list[in-1];
            --in;
        }
        list[in]= temp;
        System.out.print("The list in this step became: ");
        for (int t=0 ; t<size ; t++)
            System.out.print(list[t]+" ");
        System.out.println("");
    }
}

相关内容

  • 没有找到相关文章

最新更新