插入在Java中排序

时间:2014-08-05 04:26:07

标签: java algorithm sorting

我试图自学自己CLRS的算法简介我刚刚尝试编程插入排序算法。该算法直接来自本书,但我对我的Java代码不太自信。排序部分不正确。如果有人可以指出我的错误,那就太棒了!

public static void main(String[] args){
    int[] A = {5,6,8,9,1,2,3};
    System.out.println(Arrays.toString(A));
    InsertionSort(A);
    System.out.println(Arrays.toString(A));
}

public static void InsertionSort(int[] A){
    for(int j = 1; j < A.length; j++){
        int key = A[j];
        int i = j - 1;
        while(i > 1 && A[i] > key){
            A[i + 1] = A[i];
            i = i - 1;
        }
        A[i + 1] = key;
    }
}

1 个答案:

答案 0 :(得分:4)

public static void insertionSort(int[] A){
    for(int j = 1; j < A.length; j++){
        int key = A[j];
        int i = j; //change - don't -1
        while(i > 0 && A[i-1] > key){ //change here, must go from 0 and note change to index
            A[i] = A[i - 1]; //change here
            i = i - 1;
        }
        A[i] = key; //change here
    }
}