冒泡排序终止

问题描述 投票:0回答:1

为什么定义了循环限制,当当前值小于下一个值时,内循环结束?

我正在学习Java排序。在下面给出的代码中,您可以看到定义了内循环的限制,内循环应该从

1
运行到
arr.length-1-i
,那么为什么在当前值小于下一个值的情况下它会停止与第一个值进行比较。如果 arr[i] 不大于 arr[i+1] 为什么它停止比较当前值并转到下一个值?

这是代码

public static int[] Bubble(int arr[]){
    for(int i=0; i<arr.length-1; i++){
        for(int k = 0; k<arr.length-i-1; k++){
            if(arr[k]>arr[k+1]){
                int temp = arr[k];
                arr[k] = arr[k+1];
                arr[k+1] = temp;
            }
            printarr(arr);
            System.out.println("");
         }
    }
    return arr;
}

和输出

  7    8    2    5    9    1    6   (now you see here when comparing 7 to 8 7 is smaller)
  7    2    8    5    9    1    6   (and the the 7 isn't compared to 2, 5, 9.. to the rest of the)
  7    2    5    8    9    1    6   (elements and the iteration is stopped and is switched to 8) 
  7    2    5    8    9    1    6   (and now 8 is being compared and iterated across the array)
  7    2    5    8    1    9    6   (why?? whats the reason can anyone explain seriously its)
  7    2    5    8    1    6    9   (bothering me a lot in understanding sorting..!)
  2    7    5    8    1    6    9  
  2    5    7    8    1    6    9  
  2    5    7    8    1    6    9  
  2    5    7    1    8    6    9  
  2    5    7    1    6    8    9  
  2    5    7    1    6    8    9  
  2    5    7    1    6    8    9  
  2    5    1    7    6    8    9  
  2    5    1    6    7    8    9  
  2    5    1    6    7    8    9  
  2    1    5    6    7    8    9  
  2    1    5    6    7    8    9  
  1    2    5    6    7    8    9  
  1    2    5    6    7    8    9  
  1    2    5    6    7    8    9  
  1    2    5    6    7    8    9  
java sorting bubble-sort
1个回答
0
投票

有时,增强输出将显示交换或忽略相邻值方面发生的情况。

public static int[] Bubble(int arr[]){
    for(int i=0; i<arr.length-1; i++){
        System.out.printf("ITERATION %d%n", i+1);
        for(int k = 0; k<arr.length-1; k++){
            if(arr[k]>arr[k+1]){
                System.out.println(Arrays.toString(arr));
                int temp = arr[k];
                arr[k] = arr[k+1];
                arr[k+1] = temp;
                System.out.printf("Swapping %d and %d%n", arr[k], arr[k+1]);
                System.out.println();
            } else {
                System.out.println(Arrays.toString(arr));
                System.out.printf("Ignoring %d and %d%n", arr[k], arr[k+1]);
                System.out.println();
            }
         }
      
    }
    System.out.println();
    return arr;
}

在某些情况下,在外循环完成之前不会发生交换。在这种情况下,排序完成并且可以返回数组。这通常是通过使用初始化为

boolean
并在发生交换时设置为
true
来完成的。如果在内循环结束时该值为 true,则可以返回该数组。
    

© www.soinside.com 2019 - 2024. All rights reserved.