Java数据结构-冒泡排序

该代码示例展示了如何用Java实现冒泡排序算法,并通过设置标志变量`flag`来优化冒泡排序,当数组已经有序时可以提前结束排序,从而提高效率。代码中还使用了`Date`和`SimpleDateFormat`来计算和显示排序前后的时间差,以评估程序性能。

1、冒泡处理(将大的沉入到尾部,或者将小的沉入到尾部)。

2、冒泡处理,需要注意的点是可以提前结束循环,当一次循环都没发生时,将会提前退出循环,节约时间



import java.text.SimpleDateFormat;
import java.util.Date;


public class BubbleSortDemo {
    public static void main(String[] args) {
        int arr[] = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr[i] = (int)(Math.random()*80000);

        }
        Date date1 = new Date();
        // 进行格式化输出,时间,测试代码程序的快慢
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s1 = simpleDateFormat.format(date1);
        System.out.println("排序前:"+s1);

        bubbleSort(arr);
        // 测试冒泡程序
        Date date2 = new Date();
        String s2 = simpleDateFormat.format(date2);
        System.out.println("排序后:"+s2);
        // 冒泡6秒
//        System.out.println(Arrays.toString(arr));


    }

    public static void bubbleSort(int[] arr) {
        // 第一趟排序,就是将最大的数排在最后
        int temp = 0; // 临时变量
        boolean flag = false;// 判断是否有序

        // 确定几位数
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                // 如果前面的数比后面的数大,则交换
                if (arr[j] > arr[j + 1]) {
                    flag = true;
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
//            System.out.println("第" + (i + 1) + "趟排序后的数组:");
//            System.out.println(Arrays.toString(arr));
            if (flag == false)// 一次排序都没发生,提前结束冒泡处理
            {
                break;
            } else {
                flag = false; // 重新置为空
            }

        }


    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值