linkedList insertionsort

时间:2013-03-14 01:45:01

标签: linked-list insertion-sort

这是我使用linkedList的插入排序方法的实现。我已经尝试过它并且它可以正常工作,这是由J + 1线引起的索引超出范围异常的唯一问题。任何人都可以告诉我如何绕过它或如何解决它。 Thnx

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);
    }
}

1 个答案:

答案 0 :(得分: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("");
    }
}