Java 插入排序算法中未排序的didgit //这描述了插入排序算法 公共类InsertionSort{ 公共静态void main(字符串[]args){ //未排序整数数组 int[]数组={10,4,1,11,5,3,8,2,0,9}; int n=数组长度; 对于(int j=1;j0),并且键之前的元素大于键本身 while(i>0&&array[i]>key){ //向前移动较大的元素1块 数组[i+1]=数组[i]; //继续移动,直到元件处于正确位置 i=i-1; } 数组[i+1]=key;//将密钥分配到适当的位置 } 对于(int i=0;i

Java 插入排序算法中未排序的didgit //这描述了插入排序算法 公共类InsertionSort{ 公共静态void main(字符串[]args){ //未排序整数数组 int[]数组={10,4,1,11,5,3,8,2,0,9}; int n=数组长度; 对于(int j=1;j0),并且键之前的元素大于键本身 while(i>0&&array[i]>key){ //向前移动较大的元素1块 数组[i+1]=数组[i]; //继续移动,直到元件处于正确位置 i=i-1; } 数组[i+1]=key;//将密钥分配到适当的位置 } 对于(int i=0;i,java,insertion-sort,Java,Insertion Sort,这一行有一个问题: // this describes the insertion sort algorithm public class InsertionSort { public static void main(String[] args) { //array of unsorted integers int [] array = { 10, 4, 1, 11, 5, 3, 8, 2, 0, 9}; int n = array

这一行有一个问题:

// this describes the insertion sort algorithm
public class InsertionSort {

    public static void main(String[] args) {
        //array of unsorted integers

        int [] array = { 10, 4, 1, 11, 5, 3, 8, 2, 0, 9};

        int n = array.length;

        for ( int j = 1; j<n; j++) {
            //assign a value to the second element in the array
            int key = array[j];

            //assign a value to the 1st element in the list
            int i = j-1;

            //loop executes as long as i>0 and that the element befor the key is greater than the key itself
            while( i>0 && array[i]>key) {

                //move the bigger element 1 block forward
                array[i+1] = array[i];

                // keep moving until the element is in the right position
                i =i-1;

            }
            array[i+1] = key;//assign the key to the appropritae location
        }

         for (int i=0; i<n; i++)
                System.out.print(array[i] + " ");

            System.out.println();
    }

}
第一次迭代,j等于1,因此i等于0。循环不运行,因为0不大于零。但它应该运行,因此条件需要更改为“大于或等于零”:


这将修复您的排序。

您是否尝试调试此代码?
while( i>0 && array[i]>key) {
while( i>=0 && array[i]>key) {