简体   繁体   English

插入排序无法正常工作

[英]Insertion Sort not working properly

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

The problem is that if my input has repeated numbers, sorting fails. 问题是,如果我的输入有重复数字,排序将失败。

For int[] input ={5,3,5,3,2,1}; 对于int[] input ={5,3,5,3,2,1}; , I get 1 2 3 5 5 3 ,我得到1 2 3 5 5 3
For non-repeated numbers, sorting works fine. 对于非重复数字,排序可以正常进行。

What is wrong here ? 这是怎么了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM