冒泡排序

冒泡排序

image-20221211132053262

图解

image-20221211141628878

代码实现

package com.wiselee.sort;

import java.util.Arrays;

/**
 * @PROJECT_NAME: DataStruct
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/12/11 13:47
 * 冒泡排序
 */
public class BubbleSort {
    public static void main(String[] args) {
        int arr[] = {3,9,-1,10,-2};
        //为了容量理解,我们把冒泡排序的演变过程,给大家演示
        //第一趟排序,就是将最大的数排在最后
        int temp = 0;//临时变量
        for (int j = 0; j <arr.length-1 ; j++) {
            for (int i = 0; i < arr.length -1 -j; i++) {
                    //如果前面的数比后面的数大,就交换
                    if (arr[i] > arr[i+1]){
                        temp = arr[i];
                        arr[i] = arr[i+1];
                        arr[i+1] = temp;
                    }
            }
            System.out.println("第"+(j+1) +"一趟排序后的数组");
            System.out.println(Arrays.toString(arr));
        }
    }
}

测试性能

package com.wiselee.sort;

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

/**
 * @PROJECT_NAME: DataStruct
 * @DESCRIPTION:
 * @USER: 28416
 * @DATE: 2022/12/11 14:06
 */
public class bubble {
    public static void main(String[] args) {
        //测试冒泡排序o(n^2)
        //排序时间
        int[] arr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr[i] = (int)(Math.random()*8000000);
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-mm-dd hh:mm:ss");
        String format = simpleDateFormat.format(date);
        System.out.println("排序前的时间是"+format);
        BubbleSort(arr);
        Date date1 = new Date();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyy-mm-dd hh:mm:ss");
        String format1 = simpleDateFormat1.format(date1);
        System.out.println("排序后的时间是"+format1);
        //排序前的时间是2022-13-11 02:13:59
        //排序后的时间是2022-14-11 02:14:13
    }
    private  static  void BubbleSort(int [] arr){
        int temp = 0;//临时变量
        boolean flag = false;//表示是否进行排序
        for (int j = 0; j <arr.length-1 ; j++) {
            for (int i = 0; i < arr.length -1 -j; i++) {
                //如果前面的数比后面的数大,就交换
                if (arr[i] > arr[i+1]){
                    flag = true;
                    temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                }
            }
//            System.out.println("第"+(j+1) +"一趟排序后的数组");
//            System.out.println(Arrays.toString(arr));
            if (!flag){
                break;
            }else {
                flag = false;
            }
        }
    }
}

posted @ 2022-12-11 14:38  wiselee/  阅读(18)  评论(0编辑  收藏  举报