简体   繁体   English

插入排序程序无法正常工作

[英]insertion sort program not working properly

     public static void insertionSort(int[] arr) {

        // each outer loop iteration inserts arr[i] into the correct location of
        // the already-sorted sub-list: arr[0] through arr[i-1]

            for (int i = 1; i < arr.length; i++) {
                int valueToInsert = arr[i];
                int loc = 0;
                while (loc < i && arr[loc] < valueToInsert) { 
                    loc++;
                 }
                for (int j = loc; j < i; j++) { 
                    arr[j+1] = arr[j]; // some issue with this 
                                // loop as I'm overriding the next element
                }
            arr[loc] = valueToInsert; //// put the value 
                                       //in correct location in sub-list 
        } 
    }

Above is my insertion sort code, it is not working properly, the sample input is given below 上面是我的插入排序代码,它不能正常工作,下面是示例输入

input [3, 9, 2]
expected output is [2, 3, 9]
But I'm getting [2, 3, 3]

Please let me more about this problem regarding insertion sort and your quick response is solicited 请让我更多地了解有关插入排序的问题,并征求您的快速响应

The problem is 问题是

for (int j = loc; j < i; j++) { 
    arr[j+1] = arr[j]; 
}

The previous value in the array will cover the next one. 数组中的前一个值将覆盖下一个。 It should be 它应该是

for (int j = i-1; j >= loc; j--) { 
    arr[j+1] = arr[j]; 
}
 public class InsertionSort {

    public static void main(String...strings){
        int[] array= {3, 9, 2};
        intsertionSort(array);
    }
    public static void intsertionSort(int[] arr){
        for (int i=1; i<arr.length;i++){
            int valueToInsert =arr[i];
            int j;
            //below this is error point in your code
            for(j=i-1;j>=0 && valueToInsert <arr[j];j--)
                arr[j+1]=arr[j];
            arr[j+1]=valueToInsert;
        }
        //used for testing the function
        for(int a:arr){
            System.out.println(a);
        }
    }
}

input [3, 9, 2] 输入[3, 9, 2]

output is [2, 3, 9] 输出为[2, 3, 9]

Here is the IdeOne Link 这是IdeOne链接

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

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