插入排序无法正常工作

时间:2013-09-04 19:36:27

标签: java algorithm sorting

package sort;

public class InsertionSort {
    public static void main(String[] args) {
        int[] input ={5,3,5,3,2,1}; // the input to be sorted.
        int key; // the value that will be put into its place in the pass
        int j = 0; // indexes to be 
        int i = 0; // used for sorting


        for(j = 1; j < input.length; j++){
            key = input[j];
            for(i = j-1; i >= 0; i--){ // Look for a proper place for the key
                if(i-1 < 0){
                    if(input[i] > key){ // Have you found that place ?
                        for(int k = j;k > i; k--){ // Begin shifting
                            input[k] = input[k-1];
                        } // Done Shifting
                        input[i] = key; // Insert the key in proper place
                        break;
                    }
                }else{
                    if(input[i] > key && input[i-1] < key){ // Have you found that place ?
                        for(int k = j;k > i; k--){ // Begin shifting
                            input[k] = input[k-1];
                        } // Done Shifting
                        input[i] = key; // Insert the key in proper place
                        break;
                    }
                }
            }
        }

        for(int each : input){
            System.out.println(each);
        }
    }
}  

问题是如果我的输入有重复的数字,排序就会失败。

对于int[] input ={5,3,5,3,2,1};,我得到1 2 3 5 5 3
对于非重复数字,排序工作正常。

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

public static void main(String[] args) {
    int[] input = {12, 21, 21, 1, 4, 5, 66, 74, 0, -2, 5, 3, 5, 3, 2, 1}; // the input to be sorted.
    int key; // the value that will be put into its place in the pass
    int j = 0; // indexes to be 
    int i = 0; // used for sorting

    for (i = 1; i < input.length; i++) {
        key = input[i];
        j = i;
        while (j > 0 && input[j - 1] > key) {
            input[j] = input[j - 1];
            j--;
        }
        input[j] = key;
    }

    for (int each : input) {
        System.out.println(each);
    }
}