简体   繁体   English

为什么'i'的值打印3次,在插入排序算法中它应该只打印1次

[英]Why value of 'i' is printing 3 times, it should only print 1 time in insertion sort algorithm

//programme of insertion sort i am checking how many times the value is printing //when i enter the 2 and 1 the value of i is printing 3 times but it should have to print 1 times when i enter 2 value //插入排序程序我正在检查值打印了多少次//当我输入2和1时,我的值打印了3次,但当我输入2个值时它应该打印1次

public class Insertionsort {公共类插入排序{

static void insertsort(int arr[]){

    for(int i=1;i<arr.length;i++) {
        for(int j=i-1;j>=0;) {
            System.out.println("i is"+i);
            if(arr[j]>arr[i] ) {
                int temp=arr[j];  //for swapping 
                arr[j]=arr[i];
                arr[i]=temp;
                i--;
            }else {
                j--;
            }
        }
    }
    for(int i=0;i<2;i++) {
    System.out.println(arr[i]);
    }
}

public static void main(String args[]) {
    int arr[]=new int[2];
    System.out.println("please Enter the value");
    Scanner sc= new Scanner(System.in);
    for(int i=0;i<2;i++) {
        arr[i]=sc.nextInt();

    }
    insertsort( arr);

}

}

Output please Enter the value 2 1 i is1 i is0 i is1 1 2输出请输入值 2 1 i is1 i is0 i is1 1 2

The println should be before the inner loop. println应该在内循环之前。

for(int i=1;i<arr.length;i++) {
    System.out.println("i is"+i);
    for(int j=i-1;j>=0;) {

You only want the value of i to be printed once each time i is updated.你只想要的价值i要打印,每次当i被更新。 If you put it in the inner loop, then each value of i will be printed multiple times since the inner loop can iterate multiple times for each value of i .如果你把它放在内循环中,那么i每个值都会被打印多次,因为内循环可以为i每个值迭代多次。

For value 2,1 it's printing 3 times, because for i = 1, j= 0 it prints 1 times then goes inside if condition and makes value of i=0 and no change in value of j and now the value is 1 2 of the array as it is swap.对于值 2,1,它打印 3 次,因为对于 i = 1, j= 0,它打印1 次然后进入 if 条件并使 i=0 的值和 j 的值没有变化,现在该值为 1 2 of数组,因为它是交换。 Again it check condition for j>=0 which satisfies the for loop condition, it enter print 2nd times but this time it goes to else condition decreasing the value of j making it equal to j=-1, checks the condition and loop exit from inner loop.再次检查满足 for 循环条件的 j>=0 的条件,它第二次进入打印但这次它转到 else 条件,减少 j 的值使其等于 j=-1,检查条件并循环退出内循环。

At this point we have value of i =0, now it goes to outside loop increases value of i, ie makes value of i = 1, checks condition and then goes inside inside inner loop, with j= 0,check condition and then print 3rd times goes to else condition decreasing the value of j, breaking inner loop and then outer loop.此时我们有 i = 0 的值,现在它转到外循环增加 i 的值,即使 i = 1 的值,检查条件然后进入内循环,j = 0,检查条件然后打印第 3 次进入 else 条件,减少 j 的值,打破内循环,然后是外循环。

Try doing dry run or using debugger it will help!尝试做空运行或使用调试器它会有所帮助!

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

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