0
点赞
收藏
分享

微信扫一扫

Java - 冒泡排序 - 优化版 (BubbleSort 2.0)

天使魔鬼 2022-02-06 阅读 25
import java.util.Arrays;

public class BubbleSortTest {
    public static void main(String[] args) {
        int[] arr = {3, 5, 9, 1, 7};
        System.out.println("排序前:" + Arrays.toString(arr));
        bubbleSort(arr);
    }

    public static void bubbleSort(int[] arr) {
        int temp;
        for (int i = 0; i < arr.length - 1; i++) {
            int count = 0;  //计数 → 判断是否有交换
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    count++;  //如果有交换 → count+1
                }
            }
            if (count == 0) {
                break;  //如果不再交换 → 结束循环
            }
        }
        System.out.println("排序后:" + Arrays.toString(arr));
    }
}

输出结果:

排序前:[3, 5, 9, 1, 7]
排序后:[1, 3, 5, 7, 9]
举报

相关推荐

0 条评论