java基础算法之冒泡排序算法

冒泡排序的基本思想是:对相邻的元素进行两两比较,顺序相反则进行交换,这样每一轮循环,最大(或最小)的元素会被交换到最后的位置。

package com.example.datastructures.sort;

import java.util.Arrays;

/**
 * @author maoyouhua
 * @version jdk21
 *
 *          冒泡排序的基本思想是:对相邻的元素进行两两比较,顺序相反则进行交换,这样每一轮循环,最大(或最小)的元素会被交换到最后的位置。
 */
public class BubbleSort {

    /**
     *          基础冒泡排序,时间复杂度O(n^2)
     *
     *          flag 用来优化循环次数,当没有发生交换时提前结束排序
     *
     *          3,9,-1,10,-2       计算次数     对比次数
     *          3,-1,9,-2,10        1            4
     *          -1,3,-2,9,10        2            3
     *          -1,-2,3,9,10        3            2
     *          -2,-1,3,9,10        4            1
     *
     * @param arr   排序数组
     */
    private static void bubbleSort(int[] arr){
        //数组是从0开始算的,外层是计算次数,里层是对比次数
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            boolean flag = false;
            for (int j = 0; j < arr.length -1 - i; j++) {
                if (arr[j] > arr[j+1]) {
                    flag = true;
                    temp = arr[j+1];
                    arr[j+1] = arr[j];
                    arr[j] = temp;
                }
            }
            System.out.println("第"+ (i+1) +"次排序");
            System.out.println(Arrays.toString(arr));
            if (!flag) {
                break;
            }
        }
    }

    /**
     *      排序效率测试
     *      花费时间是:6509毫秒
     */
    private static void efficiencyTest(){
        int capacity = 80000;
        int[] arr = new int[capacity];
        for (int i = 0; i < capacity; i++) {
            arr[i] = (int)(Math.random()  * 100 * capacity);
        }
        long start = System.currentTimeMillis();
        bubbleSort(arr);
        long end = System.currentTimeMillis();
        System.out.println("花费时间是:" + (end - start) + "毫秒");
    }

    /**
     *第1次排序
     * [3, -1, 9, -2, 7, 0, 3, 8, 10]
     * 第2次排序
     * [-1, 3, -2, 7, 0, 3, 8, 9, 10]
     * 第3次排序
     * [-1, -2, 3, 0, 3, 7, 8, 9, 10]
     * 第4次排序
     * [-2, -1, 0, 3, 3, 7, 8, 9, 10]
     * 第5次排序
     * [-2, -1, 0, 3, 3, 7, 8, 9, 10]
     */
    public static void main(String[] args) {
        int[] arr = {3,9,-1,10,-2,7,0,3,8};
        bubbleSort(arr);
        efficiencyTest();
    }
}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值