0

这是我使用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);
    }
}
4

1 回答 1

0

检查此代码

只是把它作为一个类中的一个函数并尝试调用它

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("");
    }
}
于 2017-02-27T23:46:52.097 回答